【问题标题】:array input text get value数组输入文本获取值
【发布时间】:2012-04-02 04:34:02
【问题描述】:

我想在javascript中获取数组的输入文本值

这是我的代码:

Item : <input id="t_item" name="t_item[]" type="text" class="teks3">
Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3">
<input type="button" id="tb_more_item" class="add_file"/>

js代码是:

$("input#tb_more_item").click(function(){
   var new_file = $("
      Item : <input id='t_item' name='t_item[]' type='text' class='teks3'/>&nbsp;
      Cost : <input id='t_cost' name='t_cost[]' type='text' class='teks3'/>&nbsp;
   ");

   $("div#div_item").append(new_file).fadeIn();
});

我尝试使用此代码获得更多项目价值:

var item_value = [], cost_value = [];

$("input#t_item").each(function() {
   $thisItem = $(this);
   item_value = $thisItem.val();
});
$("input#t_cost").each(function() {
   $thisCost = $(this);
   cost_value = $thisCost.val();
});

alert(item_value +"-"+ cost_value );

结果是获取我在输入文本中输入的最后一个值。

有人有解决办法吗?

谢谢

【问题讨论】:

  • 但是没有发现错误..你能解决吗?如何获取输入的文本数组值?

标签: javascript arrays input


【解决方案1】:

您通过附加具有重复 ID 的元素来创建无效的 html。更新 .each() 选择器以改用 name 属性。

此外,在 .each() 函数中,您正在用当前项的值覆盖数组变量 - 也就是说,数组被丢弃并替换为该值,这就是该变量仅保存最后一个值的原因在 .each() 完成后。您要做的是将每个输入的值作为单独的元素添加到数组中:

$('input[name="t_item\\[\\]"]').each(function() {
   item_value.push(this.value);
});

t_cost 也类似。

【讨论】:

  • 这段代码不能解决问题,仍然无法获取文本输入的先前值..
猜你喜欢
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
相关资源
最近更新 更多