JavaScript after creating input element, value not shown on HTML
-
21-12-2019 - |
Question
This is my JavaScript code to create a form with multiple "input" tags.
function getStorageValues(){
if (typeof(Storage) != "undefined")
{
var myform=document.createElement("FORM");
myform.type = "post";
myform.action = "";
myform.name = "myform";
document.body.appendChild(myform);
for (var i = 0; i < sessionStorage.length; i++) {
var myinput=document.createElement("INPUT");
myinput.value = sessionStorage.getItem(i); //something wrong with this???
myinput.name = "tag" + i;
document.myform.appendChild(myinput);
}
}
However, when the form is created, I do not see the "value" attributes of any of created input fields when I do "inspect element" on browser. All I can see is:
<input name="tag0">
<input name="tag1">
<input name="tag2">
... ando so on ...
Any ideas where the "value" attribute has gone? And how to get it shown there? I can see the value inside the input field, though! But I need to have it in the code too!
P.S. Im sorry, I cannot create fiddle demo, as this is using web storage. Pasting full code is just too much.
Solution
Have you tried with the setAttribute method ?
myinput.setAttribute("value", sessionStorage.getItem(i));
Edit : you can also try to join it with an empty string in order to change the type :
myinput.value = "" + sessionStorage.getItem(i);
OTHER TIPS
sessionStorage
can't be accessed like that using a numeric key. getItem
requires a string. To get the key and access the value, you can do this:
myinput.value = sessionStorage.getItem(sessionStorage.key(i));
You can use:
myinput.setAttribute('value', sessionStorage.getItem(i))
I tried it it's working for me!