17

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" />
2
  • plain js or with jquery Commented Jun 25, 2015 at 20:09
  • You can't do that. Instead, look at binding systems like Knockout. Commented Jun 25, 2015 at 20:10

2 Answers 2

25

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Soo will the value of the input with this method be "test" or "swag"?
2

This is a better solution and will probably avoid confusion for newbies...

<!DOCTYPE html>
<html>

<body>
<h1>Input and Display Message</h1>

<p>Enter a message</p>

  <input type="text" id="msg" ><br>
  <button onclick="displayMessage()">Click me</button>


<p id="showinputhere"></p>

<script>
function displayMessage(){
    let themsg = document.getElementById("msg").value;
    if (themsg){
        document.getElementById("showinputhere").innerHTML = themsg;
    }
    else{
        document.getElementById("showinputhere").innerHTML = "No message set";
    }
}
</script>

</body>
</html>

Comments

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.