如何在javascript中调用输入id

How to call input id in javascript

本文关键字:调用 输入 id javascript      更新时间:2023-09-26

我想在这个例子上做一些javascript工作:

var str= '<td><input id="product" type="checkbox" name="product' + i + '" value="Yes" />&nbsp; new product?</td>';
str = str+'<td><input type="text"class="form-control" id="number ' + i + '" name="number' + i + '" placeholder="GTIN"</td>'

<script>
 $(document).ready(function () {
    var ckbox = $('#product');
    $('input').on('click', function () {
        if (ckbox.is(':checked')) {
            document.getElementById("number").readOnly = true;
            document.getElementById("number").value = "";
        } else {
            document.getElementById("number").readOnly = false;            
        }
    });
});
</script>

这似乎只工作,如果我的输入复选框是字符串生成器

如果我正确理解您的问题,您正在尝试检查是否检查作为字符串创建的输入。要做到这一点,你可以尝试这样做:

HTML

<div id="number">
  <table id='mytable'>
  </table>
</div>

JS

var str;
for(var i = 0; i < 4; i++){
    str = '<td><input id="product'+i+'" type="checkbox" checked name="product' + i + '" value="Yes" />new product?';
  str = str+'<td><input type="text"class="form-control" id="number ' + i + '" name="number' + i + '" placeholder="GTIN" data-checkbox-id="product'+i+'"></td>'
    $("#mytable").append(str);
}
$("[id*='product']").on("click", function(){
    var this_id = $(this).attr("id");
    if( $(this).is(":checked") )
      $("input[data-checkbox-id='"+this_id+"']").removeAttr("disabled");
    else
      $("input[data-checkbox-id='"+this_id+"']").attr("disabled", "disabled");
 });

检查小提琴:https://jsfiddle.net/koky7zj1/11/
这就是你想要的吗?

编辑
请参阅更新后的代码。我很高兴能帮上忙!:)