Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an input field using pure Javascript

Im trying to create such element only with JS:

<input type="text" value="default">

To do so, I tried this code:

var mi = document.createElement("input");
mi.type= "text"
mi.value = "default"

But when I run it in Chrome Dev Tools, it only creates this element:

<input type="text">

What am I missing?

like image 483
Enrique Moreno OB Avatar asked Jun 21 '13 11:06

Enrique Moreno OB


People also ask

How do you create a field in JavaScript?

Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.

How do you create an input element?

To create input fields, use createElement method and specify element name i.e. "input" as parameter like below and assign it to a variable. var textfield = document.


1 Answers

Setting a property of a HTMLElement isn't exactly the same as setting it's attribute to the same thing.

You most likely wanted to use element.setAttribute

var mi = document.createElement("input");
mi.setAttribute('type', 'text');
mi.setAttribute('value', 'default');

Now you can see

new XMLSerializer().serializeToString(mi);
// "<input type="text" value="default">"

In your example, the value displayed by the <input> will still be default, it just isn't set as the attribute.

Further note that if the user changes the value of <input>, e.g. types into it, setting the attribute will not change the value any longer, but setting the value property will still change it. Again, this is because an attribute is different to a property.

like image 98
Paul S. Avatar answered Sep 22 '22 05:09

Paul S.