简体   繁体   中英

why i can't change value of a text field by javascript?

I try to get my tag by tag name and change thats value, can you help me to find why this not work?

 var r_capacity=document.getElementsByName("capacity"); function expireOtherFildes(){r_capacity.value="";} 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/> capacity: <input type="text" name="capacity" value="xxx"/> 

You need to use this:

var r_capacity=document.getElementsByName("capacity")[0];

document.getElementsByName("capacity") returns an nodeList . The nodes can be accessed by index numbers.

 var r_capacity=document.getElementsByName("capacity")[0]; function expireOtherFildes(){r_capacity.value="";} 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/> capacity: <input type="text" name="capacity" value="xxx"/> 

document.getElementsByName returns array. You have access it by index.Refer below -

 var r_capacity=document.getElementsByName("capacity"); function expireOtherFildes(){ r_capacity[0].value=""; } 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/> capacity: <input type="text" name="capacity" value="xxx"/> 

You need to use

var r_capacity = document.getElementsByName("capacity")[0];

because var r_capacity = document.getElementsByName("capacity"); it's returning a nodeList and you can access that taking use of the index which is 0 :

 var r_capacity = document.getElementsByName("capacity")[0]; console.log(r_capacity); function expireOtherFildes() { r_capacity.value = ""; } 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity: <input type="text" name="capacity" value="xxx" /> 

A better approach to do it would be to use querySelector() , this will prevent from getting a problem like you encountered:

  var r_capacity = document.querySelector("input[name='capacity']"); console.log(r_capacity); function expireOtherFildes() { r_capacity.value = ""; } 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity: <input type="text" name="capacity" value="xxx" /> 

document.getElementsByName() return an array of NodeList . You need to select the first index, or simply switch to document.getElementById()

 var r_capacity=document.getElementsByName("capacity")[0]; //-^^^ console.log(r_capacity); function expireOtherFildes(){r_capacity.value="";} 
 ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/> capacity: <input type="text" name="capacity" value="xxx"/> 

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