How to assign variable to value attribute in input element?

时间:2019-01-15 18:07:21

标签: javascript html html5

I need to assign variable to value attribute in the input element

Here is my input tag.

<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">

Here is my variable.

var myValue = document.getElementById('userVal');

Anyone, please help me to fix this problem?

4 个答案:

答案 0 :(得分:1)

You can set input default value. You can not bind myValue in the html without some js framework. To get input value use change event. Check my code snippet.

var input = document.getElementById('Name');
var myValue = 'Name example';
input.value = myValue;

var myFunction = function (e) {
  console.log(e.target.value);
}
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" onchange="myFunction(event)" value="myValue">

答案 1 :(得分:0)

ASSIGN INPUT VALUE TO VARIABLE:

You need to assign the variable to the element's value, not the element itself. Also, your current input id is Name, not userVal. Change that to userVal then retrieve the value like this:

var myValue = document.getElementById('userVal').value;

Check the following Code Snippet for a practical example on how to retrieve an input value and assign it to a variable:

/* JavaScript */

document.querySelector("button").addEventListener("click", function() {
var myValue = document.getElementById('userVal').value;
alert(myValue);
})
<!-- HTML -->

<input type="text" id="userVal" class="form-control form-control-alternative" placeholder="Username">
<button>Check Value</button>

ASSIGN VARIABLE TO INPUT VALUE:

To assign your input element's value to a variable, just reverse the above assignment like this:

var newValue = newValue;
document.getElementById('userVal').value = newValue;

Check the following Code Snippet for a practical example on how to assign a variable to your input element's value attribute:

/* JavaScript */

document.querySelector("button").addEventListener("click", function() {
  var newValue = "newValue"; 
  document.getElementById('userVal').value = newValue;
});
<!-- HTML -->

<input type="text" id="userVal" class="form-control form-control-alternative" placeholder="Original" value="myValue">
<br /><br />
<button>Change Value</button>

答案 2 :(得分:0)

如果要为该输入分配值:

<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">

您应该使用以下代码:

var myValue = document.getElementById('userVal').value;
document.getElementById("Name").value = myValue;

您可以在此处查看文档和示例: https://www.w3schools.com/jsref/prop_text_value.asp

答案 3 :(得分:-1)

In JavaScript, add value property to your code as:

    var myValue = document.getElementById("name").value

In HTML, use the same id to refer the input tag as:

    <input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">
相关问题