Skip to content
Advertisement

JavaScript add another row in atable for unique id showing NAN value for id

I have a html table. Inside that my markup is like this:

JavaScript

Now under that I have a button called Add a new line:

JavaScript

in js file I have the createRow() function like this

JavaScript

Now here everything is fine. As per js I can easily add another row. But when I checked the id of input fields I saw that the first row (default one) is showing <input type="text id="prd_name1"> which one is fine. But when I clicked to the add a new line and the new created line id was <input type="text" id="prd_nameNaN">. But here I want the id should be like <input type="text" id="prd_name2"> and for 3rd row <input type="text" id="prd_name3"> like so on. Here for every new created row the number of row will be added to every field id. Here can someone kindly tell me why this issue is here? Any help and suggestions are highly appreciable.

Advertisement

Answer

document.forms[0].elements["prdprice[]"] will only return a single DOM element if there is only one instance on the page, therefore calling .length on this will return undefined:

JavaScript

Use querySelectorAll if possible instead:

JavaScript

See this fiddle demonstrating three inputs: http://jsfiddle.net/Blade0rz/3Eyba/

And this one demonstrating one: http://jsfiddle.net/Blade0rz/kqakC/

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement