问题描述:

I have a table whereby people can add rows.

There is a select input in the table that when changed, changes the values in a second select field via ajax.

The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.

I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?

The HTML form is

<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
    <tr>
        <th>Asset Type</th>
    <th>Manufacturer</th>
    <th>Serial #</th>
    <th>MAC Address</th>
    <th>Description</th>
    <th>Site</th>
    <th>Location</th>
</tr>
<tr class="removable">
    <!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
    <td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
    <td><select name="asset[0][type]">
    <option><?php echo $typeoption ?></option>
    </select></td>
    <td><select class="manuf_name" name="asset[0][manuf]">
    <option><?php echo $manufoption ?></option>
    </select></td>
    <td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
    <td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
    <td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
    <td><select id="site" name="asset[0][site]">
    <option><?php echo $siteoption ?></option>
    </select></td>
    <td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
    <td><select id="new_select" name="asset[0][contact]"></select></td>
    <!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
    <td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
    <td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
    <td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>

The script I have is

<script type="text/javascript">
$(document).ready(function() {
    $("#add").click(function() {
        var newgroup = $('#myassettable tbody>tr:last');
     newgroup
        .clone(true) 
        .find("input").val("").end()
     .insertAfter('#myassettable tbody>tr:last')
     .find(':input')
        .each(function(){
            this.name = this.name.replace(/\[(\d+)\]/,
            function(str,p1) {
            return '[' + (parseInt(p1,10)+1)+ ']'
            })

     })

            return false;         

      });


    });  

    $(document).ready(function() {
    $("#delete").click(function() {
        var $last = $('#myassettable tbody').find('tr:last')
        if ($last.is(':nth-child(2)')) {
            alert('This is the only one')
        } else {
     $last.remove()        
    }
 });
 });

$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
    $.ajax ({
        type    :   'post',
        url : 'assetprocess.php',
        data: {
        get_option  :   $(this).val()           
        },
        success: function (response) {
    document.getElementById("new_select").innerHTML=response;
}                   
            })  
        }); 
    });

</script>

and the assetprocess.php page is

<?php
if(isset($_POST['get_option'])) {

//Get the Site Contacts

$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact
<br />MySQL Error: " .mysqli_errno($dbc));

if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
    $contactid = $contactrow['contact_id'];
    $contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
    $contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}

exit;

}
?>

The code is ugly as sin, but this is only a self-interest project at this stage.

Any assistance would be greatly appreciated.

Cheers,

J.

Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/

A few minor HTML changes:

<form action="assets.php" method="post">
  <button type="button" id="add">Add Row</button>
  <button type="button" id="delete">Remove Row</button>
  <table id="myassettable">
    <tbody>
      <tr>
        <th>Asset Type</th>
        <th>Manufacturer</th>
        <th>Serial #</th>
        <th>MAC Address</th>
        <th>Description</th>
        <th>Site</th>
        <th>Location</th>
      </tr>
      <tr class="removable">
        <td>
          <select name="asset[0][type]">
            <option>---</option>
            <option>Type Option</option>
          </select>
        </td>
        <td>
          <select class="manuf_name" name="asset[0][manuf]">
            <option>---</option>
            <option>
              Manuf Option
            </option>
          </select>
        </td>
        <td>
          <input type="text" placeholder="Serial #" name="asset[0][serial_num]">
        </td>
        <td>
          <input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
        </td>
        <td>
          <input type="text" placeholder="Name or Description" name="asset[0][description]">
        </td>
        <td>
          <select id="site-0" class="chooseSite" name="asset[0][site]">
            <option>---</option>
            <option>
              Site Option
            </option>
          </select>
        </td>
        <td>
          <input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
        </td>
        <td>
          <select id="new-site-0" name="asset[0][contact]">
          </select>
        </td>
      </tr>
    </tbody>
  </table>
  <input type="submit" value="Submit">
  <input type="hidden" name="submitted" value="TRUE" />
</form>

This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.

$(document).ready(function() {
  $("#add").click(function() {
    var newgroup = $('#myassettable tbody>tr:last');
    newgroup
      .clone(true)
      .find("input").val("").end()
      .insertAfter('#myassettable tbody>tr:last')
      .find(':input')
      .each(function() {
        this.name = this.name.replace(/\[(\d+)\]/,
          function(str, p1) {
            return '[' + (parseInt(p1, 10) + 1) + ']';
          });
      });
    var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
    newId = lastId + 1;
    $("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
    $("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
    return false;
  });

  $("#delete").click(function() {
    var $last = $('#myassettable tbody').find('tr:last');
    if ($last.is(':nth-child(2)')) {
      alert('This is the only one');
    } else {
      $last.remove();
    }
  });

  $(".chooseSite").change(function(event) {
    console.log($(this).attr("id") + " changed to " + $(this).val());
    var target = "new-" + $(this).attr('id');
    /*$.ajax({
      type: 'post',
      url: 'assetprocess.php',
      data: {
        get_option: $(this).val()
      },
      success: function(response) {
        $("#" + target).html(response);
      }
      });*/
    var response = "<option>New</option>";
    $("#" + target).html(response);
  });
});

Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/

function cloneRow(n) {
  if (n - 1 < 0) return false;
  var html = "";
  html += "<tr class='removable' data-row=" + n + ">";
  html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
  html += $("#type-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
  html += $("#manuf-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
  html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
  html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
  html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
  html += $("#site-" + (n - 1)).html();
  html += "<select></td>";
  html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
  html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
  html += "</tr>";
  return html;
}

It's more work up front, yet offers a lot more control of each part. And much easier to use later.