Reputation: 25
I'd like to create a form field. And then display two variables (already assigned with values) inside it when the page loads itself. I know I can use "<input id="formField" value="John Smith"/>
but I'd like to use document.getElementById
to do this. What is wrong with my code?
The form field loads, but it is empty.
I'm very new to JS....
<!doctype html>
<html>
<body>
<input type="number" id="formField"/>
<script>
var one = "John";
var two = "Smith";
function concat() {
var x = one.value;
var y = two.value;
var z = one + "" + two;
document.getElementById("formField").innerHTML = z;
//Why doesn't this work?
}
concat();
</script>
</body>
</html>
Upvotes: 0
Views: 2621
Reputation: 494
input
elements do not have an innerHTML
property. You want to set the value
property, like so:
document.getElementById("formField").value = z;
Other things to note:
x
equal to one
and y
equal to two
, then just using one
and two
directly. No point in having x
and y
. one
and two
don't really have a value
property - they're just strings.one + " " + two
(note the space between the quotes) otherwise your ouput will be JohnSmith
Upvotes: 1
Reputation: 50336
There are couple of issues in your code
input type = "number"
but you are trying to put a string to its value. Which will not work. So change input type to textone
& two
are variables, so there is no one.value
and two.value
. Simply one + two
will work.value
instead of innerHTML
to put the value back in inputHTML
<input type="text" id="formFieldText" value=""/>
JS
var one = "John";
var two = "Smith";
function concat() {
var x = one;
var y = two;
var z = one + " " + two;
console.log(z)
document.getElementById("formFieldText").value = z;
}
concat();
Upvotes: 1
Reputation: 93
http://jsbin.com/buroxaciba/edit?html,output
innerHTML is normally used for div, span, p and similar elements.
input type number -> text
Upvotes: 0