开发者

Jquery - Loop through Checkboxes and Multiple elements

All,

I have a set of elements like this in a form:

<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]">

When a user clicks a button, I want the Javascript to:

 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.

I am new to JQuer开发者_如何学编程y..have the following code so far:

var checklimit = 50; $('#frmTest input:checkbox:checked').each(function(i) { alert(this.value); });

How do I do this using JQuery?

Thanks


Try this... it extracts out the ID from the name, then uses that to find the value and name. Demo here.

Script

$(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 ); 
  });

})


$('.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 
});​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜