Reputation:
How can i add EventListeners with JQuery/JavaScript to a varying number of elements the server returns?
The server uses a Mustache-Template engine to generate the elements:
...
{{#resource.recordEntries}}
<form action="http://x/{{entryId}}/" method="post">
<textarea id="inputArea{{entryId}}" class="inputArea">{{description}}</textarea>
<button id="saveEntry{{entryId}}" class="saveEntry" type="submit">Save</button>
</form>
{{/resource.recordEntries}}
...
For example here it returns 2 textareas and 2 buttons:
<textarea id="inputArea1" class="inputArea">Desciription Area1</textarea>
<button id="saveEntry1" class="saveEntry" type="submit">Save Area1</button>
<textarea id="inputArea2" class="inputArea">Desciription Area2</textarea>
<button id="saveEntry2" class="saveEntry" type="submit">Save Area2</button>
The critical part is the registration of the EventListeners. I could do it in a static way like this for every element, but i don't know how many elements the server returns:
$("button[id=saveEntry1]").css({"display": "none"});
document.getElementById("inputArea1").addEventListener("input", function() {
$("button[id=saveEntry1]").css({"display": "block"});
}, false);
document.getElementById("saveEntry1").addEventListener('click', function() {
$("button[id=saveEntry1]").css({"display": "none"});
}, false);
In this code example I register EventListeners to 3 textareas and buttons in a static way. What changes are necessary, that the code works more dynamic? So that it still works even if the server returns more than 3 elements.
Thanks a lot! -martin.martin
Upvotes: 0
Views: 47
Reputation: 8037
You can use the classes and bind the event to all the elements with that class.
Then you do your changes to the pressed element with $(this)
.
Like this:
$(document).ready(function () {
// Add listener for first textarea and button
$(".saveEntry").hide();
$(".inputArea").on("input", function() {
$(this).next(".saveEntry").show();
})
$(".saveEntry").on("click", function () {
$(this).hide();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="inputArea1" class="inputArea">Desciription Area1</textarea>
<button id="saveEntry1" class="saveEntry" type="submit">Save Area1</button>
<textarea id="inputArea2" class="inputArea">Desciription Area2</textarea>
<button id="saveEntry2" class="saveEntry" type="submit">Save Area2</button>
<textarea id="inputArea3" class="inputArea">Desciription Area3</textarea>
<button id="saveEntry3" class="saveEntry" type="submit">Save Area3</button>
<p> The number of textareas and buttons varies, depending on what the server returns. How can i register the listeners dynamically to all generated elements?</p>
Upvotes: 1