繁体   English   中英

使用javascript选中和取消选中动态创建的复选框时如何切换动态创建的文本框

[英]How to toggle a dynamically created textbox when dynamically created checkbox is checked and unchecked using javascript

在此处输入图片说明 我已经使用 javascript 动态创建了该表。 我需要捕获“基于复选框”的值。 检查时,应启用文本字段并捕获相应的行。

我试过

document.getElementById('chkIfSenior').onchange = function() {
document.getElementById('TEXTBOX').disabled = !this.checked;
};

但我收到此错误。

未捕获的类型错误:无法设置 null 的属性“onchange”

下面是代码:

 <!DOCTYPE html> <html> <head> <title>Add Checkbox dynamically to table cell using JavaScript</title> <style> table { width: 100%; font: 15px Calibri; } table, th, td, th { border: solid 1px #DDD; border-collapse: collapse; padding: 2px 3px; text-align: center; font-weight: normal; } </style> </head> <body> <script language="JavaScript"> function MM_openBrWindow(theURL, winName, features) { //v2.0 window.open(theURL, winName, features).focus(); } </script> Product&ensp;<input type="text" id="myInput1" onkeyup="myFunction()" placeholder="Search for Product.."> &ensp;Stock Type &ensp;<input type="text" id="myInput2" onkeyup="myFunction()" placeholder="Search for Stock Type.."> &ensp;Batch&ensp; <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Batch.."> &ensp;Storage Type&ensp;<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Storage Type.."> <br><br> <div id="container" style="width:1300px; height:500px; overflow:scroll;"> </div> <br> <input name="btnSelect" type="button" id="btnSelect" value="Draw Bin" style="width:80px;height:30px" onClick="javascript:MM_openBrWindow('demo2.html','pop', 'scrollbars=no,width=350,height=210')"> &ensp;&ensp; <input name="btnSelect" type="button" id="btnSelect" value="Close Window" style="width:150px;height:30px" onClick="javascript:MM_openBrWindow('demo2.html','pop', 'scrollbars=no,width=350,height=210')"> </body> <script> var listpagedetails = []; var request; var table = document.createElement('table'); table.setAttribute('id', 'mTable'); function myFunction() { var input, input1, input2, filter1, filter2, table, tr, td, td1, td2, td3, td4, i; input1 = document.getElementById("myInput1"); input2 = document.getElementById("myInput2"); filter1 = input1.value.toUpperCase(); filter2 = input2.value.toUpperCase(); table = document.getElementById("mTable"); tr = table.getElementsByTagName("tr"); var total = filter1 + filter2; //alert(total); for (i = 1; i < tr.length; i++) { td1 = tr[i].cells[1].innerHTML; td2 = tr[i].cells[2].innerHTML; //alert(td1+td2); // alert(total); //alert(td); td1 = td1.toUpperCase(); td2 = td2.toUpperCase(); if (td1 || td2 || td3 || td4) { // txtValue = td.textContent || td.innerText; //if (td1.toUpperCase().indexOf(filter1) > -1) { if ((td1 + td2) == (total) || (td1) == (total) || (td2) == (total)) { // alert(td1+td2); // alert(total); tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } var myApp = new function() { // An array of JSON objects with values. var jsondata; var data; var propertycontents; var di, pi; this.arrPack = [{ '': '', 'Product': '', 'Product Short Description.': '', 'Stock type': '', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' }, { '': '', 'Product': 0, 'Product Short Description.': 'Product0', 'Stock type': '1', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' }, { '': '', 'Product': 1, 'Product Short Description.': 'Product1', 'Stock type': '1', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' }, { '': '', 'Product': 2, 'Product Short Description.': 'Product0', 'Stock type': '2', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' }, { '': '', 'Product': 3, 'Product Short Description.': 'Product3', 'Stock type': '2', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' }, { '': '', 'Product': 0, 'Product Short Description.': 'Product4', 'Stock type': '3', 'Batch': '', 'Storage Type': '', 'Storage Section': '', 'Storage Bin': '', 'Avl.Qty': '', 'Uom': '', 'Batch in restr.-use': '', 'Move Qty': '' } ] this.col = []; this.createTable = function() { for (var i = 0; i < this.arrPack.length; i++) { for (var key in this.arrPack[i]) { if (this.col.indexOf(key) === -1) { this.col.push(key); } } } // Create a table var table = document.createElement('table'); table.setAttribute('id', 'mTable'); var tr = table.insertRow(-1); for (var h = 0; h < this.col.length; h++) { // Add table header. var th = document.createElement('th'); th.innerHTML = this.col[h].replace('_', ' '); tr.appendChild(th); tr.setAttribute('style', 'background-color:#777;color:#fff;'); } // Add new rows to the table using JSON data. for (var i = 1; i < this.arrPack.length; i++) { tr = table.insertRow(-1); for (var j = 0; j < this.col.length; j++) { var tabCell = tr.insertCell(-1); tabCell.innerHTML = this.arrPack[i][this.col[j]]; if (j == 11) { var tBox = document.createElement('input'); tBox.setAttribute('type', 'text'); tBox.setAttribute("disabled", true); tBox.setAttribute("id", 'TEXTBOX'); tabCell.appendChild(tBox); } if (j == 0) { // NOW HERE I AM CREATING AND ADDING A CHECKBOX TO THE TABLE CELL. var chk = document.createElement('input'); var lbl = document.createElement('label'); chk.setAttribute('type', 'checkbox'); chk.setAttribute('value', 'yes'); chk.setAttribute('id', 'chkIfSenior' + i); lbl.setAttribute('for', 'chkIfSenior' + i); // lbl.appendChild(document.createTextNode('Yes')); tabCell.appendChild(chk); tabCell.appendChild(lbl); } } } tr = table.insertRow(-1); // Create the last row. // CREATE AND ADD CHECKBOX AND TEXTBOX TO A TABLE CELLS. this.td = document.createElement('td'); // tr.appendChild(this.td); // var btNew = document.createElement('input'); // btNew.setAttribute('type', 'button'); // btNew.setAttribute('value', 'Create'); // btNew.setAttribute('id', 'New' + i); // btNew.setAttribute('onclick', 'myApp.CreateNew(this)'); // this.td.appendChild(btNew); var div = document.getElementById('container'); div.innerHTML = ''; div.appendChild(table); // Add the newlly created table to the page. }; } myApp.createTable(); </script> </html>

感谢您的评论,这对我不起作用,因为每一行的 ID 都不同。 我使用了下面的代码,但我无法启用文本框。

$('input[type="checkbox"]').click(function(){

    var table = document.getElementById("mTable");
    var tr = table.getElementsByTagName("tr");

    if($(this).is(":checked")){

        var activeRow = this.parentNode.parentNode.rowIndex;
        // document.getElementById("TEXTBOX")[1].setAttribute("disabled", false);
        $('#textbox' + activeRow).attr('disabled',!this.checked)
        // alert("Checkbox is checked.");
        alert(activeRow);
    }
    else if($(this).is(":not(:checked)")){
        alert("Checkbox is unchecked.");
    }
});

您的问题有点难以理解(未格式化的代码),但我想问题在于您试图通过错误的 ID 获取复选框。

document.getElementById('chkIfSenior').onchange = function() {...

但是在您的代码中,您通过以下方式设置 ID:

chk.setAttribute('id', 'chkIfSenior' + i);

因此,您的 ID 将如下所示: chkIfSenior0、chkIfSenior1、chkIfSenior2...

如果您检查生成的 HTML,您可以轻松检查。 调试愉快,请重新格式化您的代码

id chkIfSenior不可用,因为 id 的生成方式类似于'chkIfSenior' + i 您应该使用如下所示的查询选择器,

var list = document.querySelectorAll('[id^="chkIfSenior"]');

这将返回 id 以“chkIfSenior”开头的所有元素的列表。 然后您可以借助简单的 for 循环遍历所有元素,例如,

for (i = 0; i < list.length; i++) {
  list[i].onchange = function ...
}

@as.if.i.code
谢谢,我已将代码修改为

    $('input[type="checkbox"]').click(function(){

     var table = document.getElementById("mTable");
  var tr = table.getElementsByTagName("tr");

            if($(this).is(":checked")){

    var activeRow = this.parentNode.parentNode.rowIndex;
   // document.getElementById("TEXTBOX")[1].setAttribute("disabled", false);
         // $('textbox' + activeRow).attr('disabled',!this.checked);
         // alert(document.getElementById('textbox1').enabled);
         // document.getElementById('textbox1').enabled = this.checked;
         // $('input[name="textbox1"]').attr('enabled', this.checked);
               // alert("Checkbox is checked.");
              //  alert(activeRow);
  //alert(document.getElementById('textbox1').enabled);
  $("#textbox" + activeRow).removeAttr("disabled");
                $("#textbox" + activeRow ).focus();



            }



            else if($(this).is(":not(:checked)")){



                alert("Checkbox is unchecked.");



            }

  });

这有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM