简体   繁体   中英

Replace textbox value using javascript

I have two textboxes

<input id='random_value' name='random_name' value='First'
<input id='random_value' name='random_name' value=''

I need to replace the value of a textbox having value 'First' with 'Second' instead of using textbox id or textbox name.Is it Possible?

this function will replace the value in all input elements with "Second" if their value is "First":

function replaceTextboxValue() {
    var els = document.getElementsByTagName("INPUT");
    for(var i = 0, ceiling = els.length; i < ceiling; i++) {
        if(els[i].value == "First")
            els[i].value = "Second";
    }
}

you can make selection as follow:

var input = document.getElementsByTagName("INPUT");
var j = 0;

for (var i = 0; i < input.length; i++) {
  if (input[i].type == "text") {
      if (input[i].value == "First") {
         input[i].value == "Second"
      }
  }
}

or if you know the index of that element in dom you can directly do this as follow:

<HTML>    
<FORM>

   <input id='random_value' name='random_name' value='First'/>
   <input id='random_value' name='random_name' value=''/>
    </FORM>
</HTML>

you can set value as follow:

document.forms[0].elements[0].value=document.forms[0].elements[1].value;

if the form is first and text box is the first element of the form else you can specify the index of that instead.

if you dont know the index then you can go through the loop of all elements and check the value "First" and get it done.

You have to make a loop

 var x= document.getElementsByTagName('input');
 var i =0;
 for(i = 0; i < x.length;i++){
     if(x[i].value == "First"){
        x[i].value = "Second";
     }
 }

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