Search code examples
javascripthtmlvariablesinput

Set Input Value to Javascript Variable


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" />

Solution

  • 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>