I have a requirement where I need to capture the onchange event of a textarea. The challenge is that the textarea is dynamic, and its number can vary based on user input (e.g., single or multiple textareas).
Here is an example of how the HTML looks:
<textarea name="userInput1" id="userInput1" rows="4" cols="50" class="textareaClass"></textarea>
<textarea name="userInput2" id="userInput2" rows="4" cols="50" class="textareaClass"></textarea>
<textarea name="userInput3" id="userInput3" rows="4" cols="50" class="textareaClass"></textarea>
<!-- ... -->
<textarea name="userInputN" id="userInputN" rows="4" cols="50" class="textareaClass"></textarea>
And the jQuery code I’m using to capture the onchange event:
$(document).ready(function() {
$(".textareaClass").on("change", function() {
var textareaValue = $(this).val();
// My logic
});
});
My question is: Can I use the class attribute "textareaClass" without defining the class in the CSS? Is this considered standard practice, or is there a better way to capture the onchange event for dynamically generated textareas?
I appreciate any insights or alternative approaches to achieve this. Thank you!
2
Answers
Since you have id, you can use id starts with attribute_selectors like the following way:
Demo:
You can use
$('[id^=userInput]')
which means using id which starts with stringuserInput
, as follows: