2013-08-16 29 views
2

我有一些複選框與頁面上的標題,我想讓所有選中複選框,並對應該複選框使用jQuery的信息?如何使用Jquery獲取選中的複選框和相應的信息?

最終,我想提交一個用戶選擇的所有內容的表單。但是由於表單不知道,我需要在用戶單擊打開表單的按鈕時獲取信息。

謝謝!

<section id="myoptions"> 

<label for="123"> 
<div class="thisineed">Want this text</div> 
<div><input type="checkbox" id="123"></div> 
<div class="thisaswell">This one I want as well</div> 
</label> 

<label for="124"> 
<div class="thisineed">Want this text</div> 
<div><input type="checkbox" id="124"></div> 
<div class="thisaswell">This one I want as well</div> 
</label> 

</section> 
+0

你想要什麼格式的所有信息?它看起來像你想輸入的父標籤中的每個div的類和內容?你打算怎麼做?此外,看起來那些回答者並沒有真正閱讀過這個問題 - 迄今爲止。 – smerny

+0

你能解釋第二句話嗎?關於想要在之後做什麼? – Sergio

+0

是的。道歉,如果它不明確。基本上,我有一個用戶可以打開的表單,如果他們點擊一個按鈕。點擊發生時,我想獲取有關檢查內容的信息,並將其存儲在隱藏的textarea中,以便在表單加載並用戶提交時提交它。表單在使用fancybox的圖層中打開。我需要以某種方式得到用戶檢查的原因是複選框不是實際表單的一部分。 – user2515479

回答

4

您可以使用此到達選中的複選框:

$('input[type=checkbox]:checked').each(function(){ 
    console.log(this); 
}); 

這裏是給你一個例子。這是一個有點不清楚,你在找什麼,但檢查:

$('#get_form').click(function() { 
    $('input[type=checkbox]:checked').each(function() { 
     console.log(my_form); 
     var somevalue = $(this).parent().next('.thisaswell').text(); 
     console.log(somevalue); 
     $('#my_form').append('<input type="hidden" value="'+somevalue+'" />') 
    }); 
}); 

demo在我加入例如從後格中的文本形式產生的隱藏輸入..

+0

我的印象是['.is()'](http://api.jquery.com/is/)返回一個布爾值('true' /'false')而不是jQuery對象。我*想*你正在考慮使用'filter()',因爲你正在傳入的選擇器? –

+0

@DavidThomas,你是對的。更正! – Sergio

0

可以使用:checkbox選擇讓複選框和:checked過濾器,以獲得選中的複選框,然後使用.map()從這些複選框獲取所需的數據

var array = $('#myoptions input').filter(':checkbox:checked').map(function(){ 
    return { id: this.id, value: this.value} 
}).get() 
+0

請檢查編輯;雖然我很*確定'mao()'不是jQuery方法...;) –

+0

@DavidThomas它是一個錯字:) –

0

試試這個

var checkboxvalue=''; 
$('#myoptions input[type="checkbox"]').each(function(){ 
    var this_input=$(this); 
    if(this_input.is(':checked')){ 
    checkboxvalue += this_input.attr('value') ; 
    } 

}) 
alert(checkboxvalue) 
1

我建議:

$('#getOptions').click(function (e) { 
    e.preventDefault(); 
    var opts = $('input[type="checkbox"]').filter(function() { 
     return this.checked; 
    }).map(function() { 
     var p = $(this).closest('div'); 
     return [p.prev().text(), p.next().text()]; 
    }).get(), 
     hidden = $('<input />', { 
      'type': 'hidden' 
     }); 
    $.each(opts, function (i, v) { 
     hidden.clone().val(v).appendTo('form'); 
    }); 
}); 

JS Fiddle demo

參考文獻:

相關問題