divpinto18
divpinto18

Reputation: 25

want to display two variables using document.getelementbyid

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

Answers (3)

Richard Pressler
Richard Pressler

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:

  • You're setting 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.
  • Don't forget a space between those strings. It seems like what you want is one + " " + two (note the space between the quotes) otherwise your ouput will be JohnSmith

Upvotes: 1

brk
brk

Reputation: 50336

There are couple of issues in your code

  1. input type = "number" but you are trying to put a string to its value. Which will not work. So change input type to text
  2. one & two are variables, so there is no one.value and two.value. Simply one + two will work
  3. You have to use .value instead of innerHTML to put the value back in input

HTML

<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();

Click here for demo

Upvotes: 1

Integral
Integral

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

Related Questions