Why does javascript onchange event only work in first modal from a data table

Hello and I thank you for taking the time to read my question.

This is my first post, I have tried to be as comprehensive as possible and follow the expected requirements of posting!

My set up

I have a data table populated from a mysql database, each row has an 'Edit' button.

The 'Edit' button opens a modal with the data from the row. This all works correctly.

In the modal form, I have a 'select' dropdown element with an 'onchange' event to trigger a message.

The issue

From within the first modal (opened from the first table row's 'Edit' button) the message is triggered no problem - in the modal window linked to the first row.

But if I click on any other row's 'Edit' button to launch it's modal - and then I change the 'select' dropdown value, the message is not displayed - as if the javascript function is not being processed.

My Research so far

Having spent time googling and searching through Stack Overflow, I think the problem could be related to non-unique IDs or Class Names - and may be they should be different for each record row?

I tried to implement this by generating ID names and Class Names dynamically by using the row's ID number - so each modal had it's own unique ID for the 'select' element - but this did not fix the issue.

I am also thinking it could be a cache issue where the script is holding on to old data, but it does not matter if I click the first row on the first time, or if I click the first row after clicking several other rows before it, it is only the first row which successfully processes the onchange event.

My files


index.php (to display the data table and 'Edit' buttons)

    <table>
    <thead>
        <th>Fruit ID</th>
        <th>Fruit Name</th>
        <th>Action</th>
    </thead>
    <tbody>
        <tr>
            <td><?php echo $row['fruitID']; ?></td>
            <td><?php echo $row['fruitName']; ?></td>
            <td>
            <a href="#edit<?php echo $row['fruitID']; ?>" data-toggle="modal" class="btn btn-warning">Edit</a>
            <?php include('button.php'); ?>
            </td>
        </tr>
    </tbody>
</table>

button.php (the modal content with 'select' element and message div)

    <div class="modal fade" id="edit<?php echo $row['fruitID']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">

        <div class="row">
        <div>
            <select class="mySelector" id="mySelector" name="mySelector" onchange="show_value()">
                <option value="Apple">Apple</option>
                <option value="Orange">Orange</option>
                <option value="Banana">Banana</option>
                <option value="Mango">Mango</option>
            </select>
        </div>
    </div>

    <div class="row">
        <div id="result"></div>
    </div>
</div>
</div>

script (at the bottom of button.php to trigger the message)

<script>    
function show_value() {
        selected_value = document.getElementById("mySelector").value;
        document.getElementById("result").innerHTML = "Selected value is "+selected_value;
        }
</script>

You just need to pass your ids as parameters as shown below. Since you already have a unique id from $row['fruitID'], you can just append that number to each id so that they will be unique too.

<div class="modal fade" id="edit<?=$row['fruitID']?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
              <div class="row">
                <div>
                  <select class="mySelector" id="mySelector<?=$row['fruitID']?>" name="mySelector" onchange="show_value('mySelector<?=$row['fruitID']?>', 'result<?=$row['fruitID']?>')">
                      <option value="Apple">Apple</option>
                      <option value="Orange">Orange</option>
                      <option value="Banana">Banana</option>
                      <option value="Mango">Mango</option>
                  </select>
              </div>
          </div>

          <div class="row">
              <div id="result<?=$row['fruitID']?>"></div>
          </div>
        </div>
    </div>
  </div>
</div>

<script>    
  function show_value(input_id, output_id) {
    selected_value = document.getElementById(input_id).value;
    document.getElementById(output_id).innerHTML = "Selected value is "+selected_value;
  }
</script>

jQuery DataTables: Why click event handler does not work , However if the event handler is attached incorrectly, it will not be called for pages other than first or when the table is sorted or filtered. Clicking on “Edit” button should open a modal dialog. Event Result; JavaScript; HTML; Resources Our code above worked only for the first page elements because� The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs

You can get the select element value easily...

<script>    
    function show_value(e) { // e param is the event
        selected_value = e.value; // use e.val to get the event target value (in this case the select element value)
    }
</script>

be patient while i'm trying to process the best way to display the value

SCR19: Using an onchange event on a select element without , This technique uses the try/catch construct of JavaScript 1.4. All of the data required by the select elements is included within the Web page. When an item is selected in the first select, the choices in the other select are updated appropriately. The first There is an onchange event associated with the continent select. Pre-Select of an option in a select not working angularjs I use the following select. Currently, I get empty options in my select on start. To avoid these empty options in angularJS, I want to preselect the first option in the select. But It do not work. I get an 'Cannot read property 'conditions' of undefined'. Thank you for your

you can pass the current id in javascript by just using this.id here is an example

<input type="text" id="username" class="form-control" name="username"  onchange="formhelper(this.id)">

now in your function you can use this id as you like example

function formhelper(currentID)
{

  consolele.log('the current id is ' + currentID);
}

you can also make the id dinamically using the php tags using this example

id="<?= $value['id']?>"

HTML onchange Attribute, The other difference is that the onchange event also works on <select> elements. Applies to. The onchange attribute is part of the Event Attributes, and can be� I have a question about form submit & onchange events not working together. When I change the value on the dropdown list the event viewroom() is not firing.

HTML onchange Event Attribute, The other difference is that the onchange event also works on <select> elements. Browser Support. Event Attribute. onchange, Yes, Yes, Yes, Yes, Yes� I want it to happen when after user select the userID then the userID show up on first readonly textbox then the onChange event should fire when it show on first readonly textbox so it can copy this userID to second textbox. However it doesn't work, it only worked is the userID show up on first textbox but the onChange doesn't trigger for

jQuery Event Methods, Event methods trigger or attach a function to an event handler for the selected elements. The following table lists all the jQuery methods used to handle events. I want to do that but not immediately I have some code and if this code generate the correct result then the modal should appear if not it will not appear. – Nysa Apr 17 '16 at 4:20 no I don't want to show the result in the modal.

Native JavaScript for Bootstrap, The event.target can be the element with the data-toggle="buttons" attribute and the do something only when THE FIRST input changes // event.target is the first Since the native change event isn't consistent in most legacy browsers, with In addition, the component will also work outside the <div class="btn-group"> . Definition and Usage. The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Comments
  • You have the same id="mySelector" in every modal. IDs are supposed to be unique. getElementById("mySelector") will just select the first one.
  • Hi Barmar - thanks for your comment. As mentioned, I did try dynamic IDs so each 'select' had a unique ID like this id="<?php echo $row['fruitID']; ?> but this did not fix the issue
  • Did you change show_value() so it knows which selector to get the value from?
  • OK @Nosajimiki - I just noticed you suggested passing the parameter IDs to the modal ID and result message ID - not just the Select element ID. This does appear to be working - many thanks - I am just checking if it will work OK for other functions / validations I need to process inside the modals - but I think you may have found the solution
  • Sorry, I was missing a few closing </div> tags which may have messed things up. Also, certain special characters or value collisions in your fruitID could cause issues, but as long as you're using an auto-incremented key integer from your database as I'd assume it is, this should not be an issue.
  • For this to work you need to change it to onchange="show_value(event)"
  • I have gotten used to the frameworks as some of them do it automatically but that is 100% correct @Barmar
  • Maybe you're thinking of jQuery .on() or addEventListener, which automatically pass the event as the parameter. But if you use onXXX you have to do it explicitly.