无法通过ID从输入字段获取值

时间:2013-01-10 14:51:16

标签: jquery

我有这样的表单字段:

<input name='task_complete_percentage[]' value='' onchange='' class='percent' id='task_complete_percentage[]' style='width:40px;' type='text' />
<input name='task_complete_percentage[]' value='' onchange='' class='percent' id='task_complete_percentage1" + counter + "' style='width:40px;' type='text' />
<input name='task_complete_percentage[]' value='' onchange='' class='percent' id='task_complete_percentage2" + counter + "' style='width:40px;' type='text' />
<input name='task_complete_percentage[]' value='' onchange='' class='percent' id='task_complete_percentage3" + counter + "' style='width:40px;' type='text' />

字段是动态添加的,我想要对所有值求和。

 $('[id *= "task_complete_percentage"]').change(function(){             
 $('[id *= "task_complete_percentage"]').each( function () {
 console.log('test');
  }); 
});

但只有第一个字段正在运行,但如果这样做,我可以看到所有值。我做错了什么?

 $("#addElement").click(function(){             
 $('[id *= "task_complete_percentage"]').each( function () {
   console.log('test');
 }); 
  });

2 个答案:

答案 0 :(得分:1)

似乎不需要ID参数 - 我们可以使用其他参数/​​技术通过jQuery解决这些字段

<div id="task_complete_percentage_fields">
  <input name='task_complete_percentage[]' value='' class='percent' type='text' />
  <input name='task_complete_percentage[]' value='' class='percent' type='text' />
  <input name='task_complete_percentage[]' value='' class='percent' type='text' />
  <input name='task_complete_percentage[]' value='' class='percent' type='text' />
</div>
<div id="output"></div>
<div id="addElement">Add another row</div>

也许使用一些CSS来处理宽度,而不是为每一个设置样式属性

#task_complete_percentage_fields input.percent { width:40px }

字段是动态添加的,我想对所有值求和。

// Init the Sum Variable
var percentageSum = 0;

// Create a Function to Tally the Percentages
function sumPercentages(){
  // Reset the Sum
  percentageSum = 0;
  // Loop through the Fields
  $('#task_complete_percentage_fields input.percent').each(function(k,v){
    var $v = $(v);
    // Strip non-numerals
    $v.val( $v.val().replace( /\D/g , '' ) );
    // Sum the Percentages
    percentageSum += 1*$(v).val();
  });
  // Output the Sum
  $('#output').text( percentageSum );
}

$(document).ready(function(){

    // Attach a delegated live event to the fields within the div
    $('#task_complete_percentage_fields').on( 'change' , 'input.percent' , function(){
      sumPercentages();
    });

    // You can also call the same function from any other function
    $('#addElement').click(function(){
      $('#task_complete_percentage_fields')
        .append("<input name='task_complete_percentage[]' value='' class='percent' type='text' />");
      sumPercentages();
    });

    sumPercentages();

});

在JSFiddle上查看 - http://jsfiddle.net/lucanos/P5f4J/1/

答案 1 :(得分:0)

尝试使用这样 -

$(".percent").each( function () {
 console.log('test');
  });