简体   繁体   English

使用javascript替换文本框值

[英]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? 我需要将值为'First'的文本框的值替换为'Second'而不是使用textbox id或textbox name。这可能吗?

this function will replace the value in all input elements with "Second" if their value is "First": 如果值为“First”,则此函数将使用“Second”替换所有输入元素中的值:

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: 或者如果您知道dom中该元素的索引,您可以直接执行以下操作:

<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. 如果您不知道索引,那么您可以浏览所有元素的循环并检查值“First”并完成它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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