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 に答える