0

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

}

3 Answers 3

3

Use the setAttribute() method.

inputElement.setAttribute('readonly',true);
Sign up to request clarification or add additional context in comments.

2 Comments

It works but now the problem is its not allowing me to write anything! Is there a way we can check if the element has been appended. if its true only then it should be set to readonly property
If you can reach the element through the DOM it has been appended. For instance, if you do document.getElementById('foo') and get null then there is no element with the ID of 'foo'.
0

JavaScript is case sensitive.

t2.readOnly = true;

Comments

0

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.

2 Comments

I have to do this using javascript
Also I tried your code as well. It isn't allowing to write anything! because of the readonly attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.