简体   繁体   中英

Insert Rows to Table using Javascript

I am trying to add rows dynamically in my HTML table and its working fine. Now what I am trying to do is, I want to make them non-editable. That is, once they are created, they should behave as normal <tr> <td> elements! I tried assigning the readonly property after appending but it didn't work.

The HTML

<!DOCTYPE html>
<html>
<head>
<script src = "myScripts.js" type = "text/javascript"></script>

</head>
<body>


<table id="myTable" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>

</table><br>

<button onclick="addRow()">Add Row</button>

</body>
</html>

the Javascript:

var index = 1;
function addRow(){
            var table=document.getElementById("myTable");
            var row=table.insertRow(table.rows.length);
            var cell1=row.insertCell(0);
            var t1=document.createElement("input");
                t1.id = "txtName"+index;
                cell1.appendChild(t1);
            var cell2=row.insertCell(1);
            var t2=document.createElement("input");
                t2.id = "txtAge"+index;
                cell2.appendChild(t2);
        //t2.readonly = "readonly";
      index++;

}

使用setAttribute()方法。

inputElement.setAttribute('readonly',true);

JavaScript is case sensitive.

t2.readOnly = true;

I will recommend the use of jQuery as it drastically reduces the lines of code.

I have used the readOnly attribute as below.

Please see the Demo here

HTML:

<table id="myTable" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>

</table><br><button id="addRow">Add Row</button>

JS:

var i=1;

$('#addRow').click(function(){   
    var appendString = "<tr><td><input type='text' id='txtName"+i+"' readonly='readonly' /></td><td><input type='text' id='txtAge"+i+"' readonly='readonly' /></td></tr>";

    $('#myTable tr:last').after(appendString);    
    i++;
});

See the code is reduced drastically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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