Reputation: 47
I am trying to set value to my input but I want to do this while my data ends. As you know id must be unique in html. So i created an 'element' variable and I am increasing it. I want to make my input text my model's CustomerName.
That's my code.
var element = 0;
var HTML = "";
while (element !== 5) {
HTML += "<input id=senderName" + element + " class=senderNameText type=text>";
document.getElementById("senderName" + element).value = "@Html.DisplayFor(model => model.CustomerName)";
element++;
}
div.innerHTML = HTML;
document.body.appendChild(div);
When I check it at console in Chrome it is written as "Cannot set property 'value' of null".
What should I do.
Thanks.
Upvotes: 1
Views: 3596
Reputation: 67505
Your code should be like the following (note the quotes '
in creation of he new inputs are necessary) :
var element = 0;
var HTML = "";
while (element !== 5) {
div.innerHTML = "<input id='senderName" + element + "' class='senderNameText' type='text'>";
document.body.appendChild(div);
document.getElementById("senderName" + element).value = "@Html.DisplayFor(model => model.CustomerName)";
element++;
}
Now the problem come when you try to select new elements from the document
and you're not yet append them so you get the message error that mean JS can't find any elements by the ids
you're given.
So you should append the new HTML to the DOM inside loop.
Hope this helps.
Upvotes: 1