Issue
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!
Solution
Since you have id, you can use id starts with attribute_selectors like the following way:
('textarea[id^=userInput]').on("change", function() {...
Demo:
$(document).ready(function() {
$('textarea[id^=userInput]').on("change", function() {
var textareaValue = $(this).val();
console.log(this.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Answered By - Mamun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.