Set Input Value to Javascript Variable

2019-06-24 00:25发布

问题:

Let's say I have a variable called x in javascript. How can I set the value of a text input (HTML) to that variable? For example:

The value of the input will now be Swag

<input type="text" value="Swag" />

But if I want the value to be a javascript variable? How do I do? Something like this? (I am just guessing, trying to make my point clear)

<input type="text" value="variable.x" />

回答1:

You can set it in your javascript code like:

<input id="myInput" type="text" value="Swag" />

<script>
    var test = "test";
    document.getElementById("myInput").value = test;
</script>