1

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?

0

3 Answers 3

3

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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

He is asking for a selection based on the value, not how to set the value for a specific element (like islandmyth answered)
I need to replace the textbox value with 'First' to 'Second'
@DavidMulder he can make selection based on value by looping all textboxes in dom see my edit.
Yeah, the clue was the looping not all the other stuff which he apparently (based on the question) already was able to do.
0

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";
     }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.