Change function doesn't fire a second time on drop down list

I’ve created a csv import feature so that users can upload a csv file, choose from a drop down list what content each collumn contains and then it will be sent to the database. I’m using jquery to change the name attribute in each input field. It works great for the first choice but if the user makes a wrong choice or changes their mind it does not change the name attribute a second time. Here is the code:

$("select").change(function () {
      var fieldName = $(this).attr('name');
      var optionValue = $(this).val();
      $('input[name=' + fieldName + ']').attr('name', optionValue);

Any ideas?

Is the select box changing in any way?

If it is that it why the event is not working anymore as DOMEventListiners can only target elements that already exist in the DOM, try the below code.

$('select').on('change', function() {
    // Code here...

Once you change the name of the input, the name has changed from what it used to be, which is why the function cannot find it in order to change it again.

A potential solution is to assign a reference to the field to the select element (via the this keyword), and use that instead.
We can do that by checking if the select already has a reference. If it doesn’t (which would be the 1st time) we give it a reference to the field.

$("select").change(function () {
    var fieldName = $(this).attr('name'),
        field = $('input[name=' + fieldName + ']'),
        optionValue = $(this).val();
    this.inputfield = this.inputfield || field;
    this.inputfield.attr('name', optionValue);

Yes of course, that makes sense. I changed the name of the input so of course it isn’t going to find it the second time. Thank you, I’m going to try your suggestion now.