16

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?

2
  • Can you put in the code you're using to insert the element into the DOM as well? Commented Jun 21, 2013 at 11:33
  • 1
    What's wrong, doesn't the value show up in the page or on submitting? Commented Jun 21, 2013 at 11:35

3 Answers 3

34

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: To set or modify the current values, you should use the properties when possible. For example, use elt.value = val instead of elt.setAttribute('value', val), due to inconsistencies across browsers and environments, most notably XUL and IE (IE with the use of class instead of className). Do a little search if you wish to know/understand more. +1. The OPs code should work fine though: jsfiddle
5
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
i.setAttribute('value',"default");

Comments

1

I think you are missing the ; after "text".

1 Comment

semicolons are not required... but preffered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.