Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" />
like image 272
JakeTheSnake Avatar asked Jun 25 '15 20:06

JakeTheSnake


People also ask

How do you assign a value to a variable in JavaScript?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

How do you get input value directly in JavaScript?

We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.

How do I set default input value?

The Input Text defaultValue Property in HTML DOM is used to set or return the default value of the Text Field. This property is used to reflect the HTML value attribute.

Can I change input type JavaScript?

To change the type of input it is (button to text, for example), use: myButton. type = "text"; //changes the input type from 'button' to 'text'. Another way to change or create an attribute is to use a method like element.


2 Answers

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>
like image 95
agent_smith1984 Avatar answered Sep 18 '22 03:09

agent_smith1984


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>
like image 45
brso05 Avatar answered Sep 20 '22 03:09

brso05