1

I have built a form and there is a part where there is an "add row" button which adds another row of inputs (if the user needs it).

However on this row there is a select input that needs a change handler. So what I have done, is every time the button to add a new row is clicked, each of the select inputs (which have the same name attribute) are given a unique id like so

let creditorInputs = $('select[name="creditors"]');
console.log(creditorInputs);

creditorInputs.map(i => {
$(creditorInputs[i]).attr('id', `creditorSelect${i}`);

This gives them an id of "creditorSelect0, creditorSelect1" etc

But further down the loop I have added a change listener and when I click on the select input an change its value, it only seems to affect the first one on the page.

Here is the full script:

$('#addrowothermort').click(() => {
    let creditorInputs = $('select[name="creditors"]');
    console.log(creditorInputs);

    creditorInputs.map(i => {
        $(creditorInputs[i]).attr('id', `creditorSelect${i}`);

        $(`#creditorSelect${i}`).change(() => {
    
            console.log("Changed");
            
        });

    });
});

EDIT:

$('#tabs-6').click(event => {
        event.preventDefault();
        
        if(event.target.name == 'creditors') {
            let rightInput = event.target;
            
            rightInput.addEventListener('change', () => {
                console.log(rightInput.value);
            })
        }
    })
Spring
  • 12,325
  • 4
  • 30
  • 43
BranOIE
  • 226
  • 10
  • Use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](https://stackoverflow.com/tags/event-delegation/info) and [What is DOM Event delegation?](https://stackoverflow.com/q/1687296/4642212). – Sebastian Simon Feb 23 '21 at 09:42
  • @SebastianSimon I understand the concept but not sure how to apply it in this case. The inputs arent all in the same div – BranOIE Feb 23 '21 at 09:52
  • _“The inputs arent all in the same div”_ — But they all have _some_ lowest common ancenstor. – Sebastian Simon Feb 23 '21 at 09:55
  • @SebastianSimon I have made an edit, seems like I'm getting there. But now the `console.log(rightInput.value)` executes numerous times, sometimes 2, 3, 4 or 5. Not sure why this is – BranOIE Feb 23 '21 at 10:14
  • you should find your answer here: https://stackoverflow.com/questions/19481805/jquery-change-event-does-not-fire-for-dynamic-generated-dropdown – Muhammad Murad Haider Feb 23 '21 at 11:37

1 Answers1

0

embeding event to each select in a loop will attach again and the again the event ,

so wether using event delegation outside the loop , or attach event to dreclyt created input withot loop ,

What a suggest is bit changing the logic , create function that creates input and and embed the click to it , after that calculate the number of creator input and set the id for the newly create depending on number of inputs .

See below snipet :

var arr = [{
    val: 1,
    text: 'One'
  },
  {
    val: 2,
    text: 'Two'
  },
  {
    val: 3,
    text: 'Three'
  }
];

function createSelect(arr) {
  var select = $('<select>').appendTo('#container');
  $(arr).each(function() {
    select.append($("<option>").attr('value', this.val).text(this.text));
  });
  return select;
}
$('#addrowothermort').click(() => {

  let $select = createSelect(arr);

  $select.attr("name", "creditors");
  let selectLength = $('select[name="creditors"]').length - 1 | 0;

  $select.attr("name", "creditors");
  $select.attr("id", selectLength);

  $select.on("change", function() {

    console.log("Change in ", $(this).attr("id"));

  });


});
select {
  margin: 5px 20px 0px 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addrowothermort">add row </button>


<div id="container"></div>
Spring
  • 12,325
  • 4
  • 30
  • 43