2013-02-20 20 views
1

我想在jQuery中點擊一個提交按鈕時獲取所選複選框的數組,我似乎無法獲取任何內容。獲取jQuery中選定複選框的值

jQuery的:下面的代碼

$(".btn").live("click",function() { 
    var ffirst = $('input:checkbox[name="first[]"]:checked').map(function() { 
     return this.value; 
    }).get(); 
}); 
$.each(ffirst, function(index, value) { 
    alert(index + ': ' + value); 
}); 

及以下HTML:

<input type="checkbox" value="1" checked="checked" name="first[]"> 
<input type="checkbox" value="2" checked="checked" name="first[]"> 
<input type="button" class="btn" value="Go"> 

任何幫助,將不勝感激!

編輯:改變了每個評論,但仍然損壞。

+0

哪一個是你的Jquery版本? – FabianoLothor 2013-02-20 17:21:40

回答

0

你用過不好選擇,使用:

$('input:checkbox[name="first[]"]:checked') 

live demo

+0

不幸的是,這不起作用,請參閱上文。 – OneAndTwo 2013-02-20 17:21:31

+0

是的,這是作品!檢查附帶的演示 – vlcekmi3 2013-02-20 17:23:04

+0

是的,你是對的,謝謝! – OneAndTwo 2013-02-20 17:33:05

0

您的JS:

name=first 

你的HTML:

name="first[]" 

這些不匹配。

添加方括號。你還需要引用他們,因爲他們不是字母數字。

$('input:checkbox[name="first[]"]:checked') 
+0

不幸的是,這似乎並不奏效。 – OneAndTwo 2013-02-20 17:21:13

+0

當我測試它時,它做到了。 – Quentin 2013-02-20 17:21:34

+0

例如:http://jsbin.com/axecum/1/ – Quentin 2013-02-20 17:22:34

0

嘗試:

$(".btn").on("click",function() { 
    $('input:checkbox[name="first[]"]:checked').each(function(index) { 
     alert(index + ': ' + this); 
     console.log(this); 
     console.log($(this)); 
    }); 
}); 

只要使用(.live)如果真的需要

0

你需要聲明第一個數組befo重新點擊處理程序,因爲它超出了範圍。每個循環都必須在click處理程序中發生,因爲一旦數組被填充,它將需要執行。

不是最優化的代碼,但這裏有一個工作的例子:

var ffirst = []; 
$(".btn").live("click",function() { 
    ffirst = $('input[name="first[]"]:checked').map(function() { 
    return $(this).val(); 
    }); 

    $.each(ffirst, function(index, value) { 
    alert(index + ': ' + value); 
    }); 
}); 

Working Demo