简体   繁体   中英

Reference to the value of input field

Consider the following code snippet:

inputTextField=document.getElementById("Phone_input");
var value = inputTextField.value; 
value=value.substring(0,10);

where Phone_input is an <input type="text"/> element. Why during the running of this script there is no changes of actual value of the <input type="text"/> . We're changing value by the reference which indicates to inputTextField.value .

The variable value is not a reference, so after the change you must write it back into the textfield:

value=value.substring(0,10);
inputTextField.value = value;

Or, in one line:

inputTextField.value = inputTextField.value.substring(0,10);

Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents. In this case you have to do it this way:

var inputTextField=document.getElementById("Phone_input");
inputTextField.value = inputTextField.value.substring(0,10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM