Javascript Jquery.on(更改)事件on<;选择>;仅输入更改第一行。

Javascript Jquery.on(更改)事件on<;选择>;仅输入更改第一行。,javascript,php,jquery,html,mysql,Javascript,Php,Jquery,Html,Mysql,我有一张桌子,人们可以在上面添加行 表中有一个select输入,当更改时,它会通过ajax更改第二个select字段中的值 我遇到的问题是,如果一个人向表中添加了一行,则.on(change)事件会更改第一行中的第二个字段,而不是下一行 我一直在绞尽脑汁,试图弄清楚是否需要(如果需要,如何)动态更改事件绑定到的div id及其影响的div。这就是解决办法吗?如果是这样的话,有人能证明我是如何做到这一点的吗 HTML表单是 <form action="assets.php" method="

我有一张桌子,人们可以在上面添加行

表中有一个select输入,当更改时,它会通过ajax更改第二个select字段中的值

我遇到的问题是,如果一个人向表中添加了一行,则.on(change)事件会更改第一行中的第二个字段,而不是下一行

我一直在绞尽脑汁,试图弄清楚是否需要(如果需要,如何)动态更改事件绑定到的div id及其影响的div。这就是解决办法吗?如果是这样的话,有人能证明我是如何做到这一点的吗

HTML表单是

<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>

添加行
删除行
资产类型
制造商
连载#
MAC地址
描述
场地
位置
我的剧本是

<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>

$(文档).ready(函数(){
$(“#添加”)。单击(函数(){
var newgroup=$(“#myassettable tbody>tr:last”);
新闻组
.clone(真)
.find(“输入”).val(“”.end()
.insertAfter(“#myassettable tbody>tr:last”)
.find(“:输入”)
.each(函数({
this.name=this.name.replace(/\[(\d+)\]/,,
功能(str,p1){
返回'['+(parseInt(p1,10)+1)+']
})
})
返回false;
});
});  
$(文档).ready(函数(){
$(“#删除”)。单击(函数(){
var$last=$(“#myassettable tbody”).find('tr:last')
如果($last.is(':第n个子项(2)')){
警报('这是唯一一个')
}否则{
$last.remove()
}
});
});
$(文档).ready(函数(){
美元(“#我的资产”)。关于(“更改”、“站点”、功能(事件){
$.ajax({
键入:“post”,
url:'assetprocess.php',
数据:{
get_选项:$(this.val())
},
成功:功能(响应){
document.getElementById(“新建选择”).innerHTML=响应;
}                   
})  
}); 
});
并且assetprocess.php页面是

<?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\n<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;

}
?>
工作示例:

一些小的HTML更改:

<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>
通过在全局空间中为行数设置计数器,可以节省一些时间,例如
var trCount=1
并使用它设置数组索引和ID。克隆既快又容易,但也意味着我们必须返回并附加各种属性。还可以为您制作一个函数来绘制HTML。比如:

函数cloneRow(n){
如果(n-1<0)返回false;
var html=“”;
html+=“”;
html+=“”;
html+=$(“#type-”+(n-1)).html();
html+=“”;
html+=“”;
html+=$(“#manuf-”+(n-1)).html();
html+=“”;
html+=“”;
html+=“”;
html+=“”;
html+=“”;
html+=$(“#site-”+(n-1)).html();
html+=“”;
html+=“”;
html+=“”;
html+=“”;
返回html;
}

这是更多的工作在前面,但提供了更多的控制每个部分。而且以后更容易使用。

阅读以
委托事件开头的段落,其优点是它们可以处理来自后代元素的事件。
文档()上的html ID必须是唯一的。克隆行时,会添加具有相同ID的重复元素,其中包括
现在您已经破坏了dom,不可预知的事情就会发生。而是使用类,这些类可以是duplicated@OfirBaruchOP正在使用事件委派,只需创建重复的IDSDLE:Wow。令人惊叹的。非常感谢你。这就解决了问题。我还没有足够的理由公开我的投票结果,但我已经投票决定了答案。再次感谢你。
$(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);
  });
});
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;
}