从文本框数组中选择一个文本框

时间:2013-12-27 12:17:42

标签: javascript jquery jquery-selectors

我想从文本框数组中选择一个文本框。 为此我尝试了以下方法,但我没有得到任何输出

HTML代码

<input type="text" id="total[]"/>
<input type="text" id="total[]"/>
<input type="text" id="total[]"/>

jquery

$i=0;
for($i = 0;$i < total.length;$i++;)
{
 $("#total\\[$i\\]").val($i);   
}

上面的代码没有显示任何内容。

请帮我解决问题

修改

我已经更新了我的演示,

textbox at pos(0,2) total of(0,0) and (0,1) should come
textbox at pos(1,2) total of(1,0) and (1,1) should come
and
textbox at pos(2,0) total of(0,0) and (1,0) should come
textbox at pos(2,1) total of(0,1) and (1,1) should come

Demo

5 个答案:

答案 0 :(得分:2)

要将input应用于数组以进行服务器端处理,您必须使用name属性。 id属性在文档范围内必须是唯一的。如果你有这个标记:

<input type="text" name="total[]"/>
<input type="text" name="total[]"/>
<input type="text" name="total[]"/>

您可以通过将函数传递给val()方法来实现您想要的效果:

$('input[name^=total]').val(function(i){
   return i;
});

JSFiddle

答案 1 :(得分:0)

当您为多个控件分配相同的ID时,以及当您尝试使用jQuery或javascript获取它们时,您只能获得它们的第一次出现。

你应该为你的控件提供不同的ID,并一次性获取它们,尝试使用tagName选择它们或给它们一个uinque类然后选择

试试这个:

<input class='operate' type="text" id="input1"/>
<input class='operate' type="text" id="input2"/>
<input class='operate' type="text" id="input3"/>

和你的jQuery代码

   $('input[type=text]').each(function(index,elem){
         this.value = index;
   });

   $('input.operate').each(function(index,elem){
          this.value = index;
   });

答案 2 :(得分:0)

试试这个:

$("[id^='total']").each(function(){
   alert($(this).attr("id"));//You will get id of all textbox here
});

DEMO

答案 3 :(得分:0)

为每个输入提供相同的类,然后迭代它: Javascript

var i=0;
$(".txtbox").each(function(){
$(this).val(i++);
});

Html

<input type="text" class="txtbox"/>
<input type="text" class="txtbox"/>
<input type="text" class="txtbox"/>

检查小提琴here

答案 4 :(得分:0)

使用name属性。

<强> HTML

<input type="text" name="total[]"/>
<input type="text" name="total[]"/>
<input type="text" name="total[]"/>

<强>的JavaScript

使用 .eq 进行选择。

var $textboxes = $('input[name="total[]"]')

var value1 = $textboxes.eq(0).val();
var value2 = $textboxes.eq(1).val();
相关问题