I have this (bootstrap) form with three elements. As the button is clicked, another line with three elements is added.
<div class="row align-items-center mb-2 mt-2 ms-1 ">
<div class="col-5 ps-1 pe-1">
<select class="form-select example-select" id="cmbSelect[]" name="cmbSelect[]">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div class="col-4 ps-1 pe-1">
<input class="form-control" type="text" name="txtFirst[]">
</div>
<div class="col-2 ps-1 pe-1">
<input class="form-control" type="text" name="txtSecond[]" value="3">
</div>
<div class="col-1 ps-1 pe-1">
<a href="javascript:void(0);" class="add_button" title="Add one more element"><img src="../img/add-icon.png"/ alt="Add"></a>
</div>
</div>
I would like to execute a JS function if the first element cmbSelect[] is clicked. The function must get the element that triggered the event, because its selected item should be edited. Furthermore the value of the element next to the one that triggered the event should be updated.
What is the best way doing this?
I tried something like this:
var example_select = $(".example-select");
var all = $(".example-select").map(function() {
this.on("click", function (element) {
console.log("clicked");
return element.innerHTML;
});
}).get();
console.log(all.join());
But example_select is empty and the click event is not fired...
console.logto check if the event is fire, but not spotting the huge error in the console. Not only check the console for errors, but make sure you aren't filtering errors out of your console. Test withconsole.error("test")return element.innerHTML;to return to the map? (would explain the all.join() ).returnonly returns to the nearestfunction, in this case the click handler. Also, the .map would return immediately (and thus the .get() / .join()) while the click event will fire sometime in the future.on(from the answer below) runs on doc.ready (where it should, or at the end of the document) then it will only work for any existing elements. It won't work for newly added lines via the "add" button. You need event delegation. See: Event binding on dynamically created elements which is likely your actual issue.