0

我有这样的表单字段:

<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');
 }); 
  });
4

2 回答 2

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/

于 2013-01-10T15:15:05.893 回答
0

尝试这样使用——

$(".percent").each( function () {
 console.log('test');
  }); 
于 2013-01-10T14:56:10.057 回答