Ayush Srivastava Ayush Srivastava - 4 months ago 13
HTML Question

use 'id name ends with' inside on() for dynamic binding

I have multiple select type input HTML fields getting dynamically generated inside my form. I want to dynamically bind the item field to the change event.

item field looks like this:

the id of item field generated is like this


  • id="id_form-0-item"

  • id="id_form-1-item"

  • id="id_form-2-item"

  • ...



I have tried this but it doesn't work.

</script>
$(document).on('change','select[id$='item']', function(event){
alert(event.target.id);
});
</script>


I want the id of element which triggered the event. Thanks

Answer

You have a typo in your function: char escape. You need to change:

$(document).on('change','select[id$='item']', function(event){

to:

$(document).on('change','select[id$="item"]', function(event){

another way to escape char is:

$(document).on('change','select[id$=\'item\']', function(event){

For more info you may take a look to Escape notation in string So the snippet is:

$(function () {
  $(document).on('change','select[id$="item"]', function(event){
    console.log("event.target.id=" + event.target.id + " or this.id=" + this.id);
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<select id="id_form-0-item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<select id="id_form-1-item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<select id="id_form-2-item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Comments