Jquery - 循环复选框和多个元素

时间:2010-06-07 21:45:10

标签: javascript jquery

所有

我有一组这样的元素:

<input type="checkbox" name="chk[140]">
<input type="hidden" value="3" name="ctcount[140]">
<input type="hidden" value="Apples" name="catname[140]">

<input type="checkbox" name="chk[142]">
<input type="hidden" value="20" name="ctcount[142]">
<input type="hidden" value="Bananas" name="catname[142]">

<input type="checkbox" name="chk[144]">
<input type="hidden" value="200" name="ctcount[144]">
<input type="hidden" value="Strawberries" name="catname[144]">

<input type="checkbox" name="chk[145]">
<input type="hidden" value="0" name="ctcount[145]">
<input type="hidden" value="Carrots" name="catname[145]">

当用户点击按钮时,我想要Javascript:

 1. Loop through all the checkboxes
 2. For all the checked checkboxes, 
     2a. Get ctcount value
     2b. Get catname value
     2c. If ctcount value > 50, alert a message saying "Unable to add item
          as max limit for 'catname' has reached.
     2d. Break the loop after it encountered first ctcount value that is 
         greater than 50.

我是JQuery的新手。到目前为止,我有以下代码:

var checklimit = 50; $('#frmTest input:checkbox:checked')。each(function(i){                 警报(THIS.VALUE);             });

如何使用JQuery执行此操作?

由于

2 个答案:

答案 0 :(得分:1)

$('.button').click(function() {
     var sum = 0;
     var cancel = false;

     $('input[type="checkbox"]:checked').each(function() {
          if(cancel)
              return;

          var count = parseInt($(this).next().attr('value'));
          var name = $(this).next().next().attr('value');
          sum += count;

         if(sum > 50) {
               alert('no way dude');
               cancel = true;
               return;
          }
     });

     if(!cancel)
         // sum <= 50 
});​

答案 1 :(得分:1)

试试这个...它从名称中提取出ID,然后用它来查找值和名称。 Demo here

脚本

$(document).ready(function(){

  $(':button').click(function(){
    var total = 0, done = false;
    $(':checked').each(function(){
      if (!done) {              
        var catid = $(this).attr('name').replace(/chk\[(\d+)\]/,'$1'); // extract #
        var catval = parseInt( $('input[name=ctcount\[' + catid + '\]]').val(), 10);
        var catnam = $('input[name=catname\[' + catid + '\]]').val();
        if (total + catval > 50) {
          alert('Unable to add item as max limit for "' + catnam + '" has reached');
          done = true;
        } else {
          total = total + catval;
        }
      }
   })
   alert( 'The total is ' + total ); 
  });

})