2010-06-07 21 views
1

所有,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..have下面的代碼至今:

VAR checklimit = 50; (函數(i){alert(this.value); });

如何使用JQuery執行此操作?

感謝

+0

你有什麼企圖這麼遠嗎? – 2010-06-07 21:58:30

回答

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

}) 
+0

這個效果很好..除了我們不需要總數.. :) – Jake 2010-06-08 16:17:48

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 
});​ 
+0

謝謝..我們不能使用元素名稱而不是$(this).next()嗎?如果HTML中元素的順序發生變化,這可能會中斷。 – Jake 2010-06-07 22:05:08

+0

$(this)將起作用。如果你開始移動東西,next()將會中斷。爲了避免使用next(),你必須從複選框名稱中抽取字符串或捕獲字段編號,並使用它來構造隱藏的字段名稱。 – 2010-06-07 22:07:47