2016-12-04 110 views
3

我知道這個問題已被詢問很多次,並且我已經找到了一些關於如何從複選框中獲得text()的答案,但是當我試圖僅從選中的文本中獲取文本時,我的代碼出現了一些錯誤。如果選中複選框,如何獲取文本()?

考慮以下代碼:

$('input.choose-age').on('change', function() { 
 
    $('input.choose-age').not(this).prop('checked', false); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="checkbox"> 
 
    <label for='wom-10-14' class="checkbox-inline"> 
 
\t <input type="checkbox" id='wom-10-14' class='choose-age' checked />10-14 
 
    </label> 
 
    <label for='wom-15-19' class="checkbox-inline"> 
 
\t <input type="checkbox" id='wom-15-19' class='choose-age' />15-19 
 
    </label> 
 
    <label for='wom-10-19' class="checkbox-inline"> 
 
\t <input type="checkbox" id='wom-10-19' class='choose-age' />10-19 
 
    </label> 
 
</div>

我想,如果被選中從複選框選擇text()並保存到一個var。我使用d3.jsmapbox來運行mapDraw函數,因此如果選中了不同的複選框,我想更改指示符。

我知道,這個例子返回文本,但是是不是我要找:

var ageLab = $('label[for=wom-10-14]').text(); 

這是我的嘗試:

var ageLab = $('input:checkbox:checked').map(function() { 
    return $(this).prev('label.checkbox-inline').text(); 
}).get(); 

console.log(ageLab); 

來源:example 1

它返回:

Array[1] 
    0: "" 
    length: 1 

var ageLab = $('.choose-age:checked').text(this.checked ? $(this).text() : ''); 

來源:example 2

然而,doesn't返回文本。

有沒有更好的方法來檢查時從複選框中獲得text()

在此先感謝!

回答

3

沒有.text()或複選框元素的文本屬性,因爲它們是空的。要麼你可以得到它們的價值,如果定義的話,否則,我們可以採取不同的方法。

最近

var ageLab = $('input:checkbox:checked').map(function() { 
    return $(this).closest('label.checkbox-inline').text(); 
}).get(); 

跨度

<input type="checkbox" id='wom-10-14' class='choose-age' checked /> <span>10-14</span> 
var ageLab = $('input:checkbox:checked').map(function() { 
    return $(this).next('span').text(); 
}).get(); 

注:如果你想只有一個選擇,爲什麼不走對於:radio而不是:checkbox

+1

優秀。謝謝,@Praveen。 'span'好得多,':radio'也是更好的選擇。 – estebanpdl

相關問題