简体   繁体   中英

Element not taking string values

I have a html page containing two textboxes with id name and mobile.

I've created a list and inserted the values into it.But its not taking the name value, its only taking the mobile textbox value. The other part is shown as undefined.

This is the code.

var li = document.createElement("li");
li.textContent = name.value +" , "+mobile.value;
list.appendChild(li);

What is the error ?

"name" is a poor name for a field since if you do not qualify is like document.getElementsByName("name")[0] it could be window.name -

If the field has id="name" then use document.getElementById("name") instead since most browsers do not copy the ID attribute to the window scope

Thus

var li = document.createElement("li");
li.textContent = document.getElementById("name").value +" , "+
  document.getElementById("mobile").value; 
list.appendChild(li);

I also personally prefer li.innerHTML since it works in all browsers

Lastly remember that IDs must be unique

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