1. 程式人生 > >用jquery獲得選擇的checkbox的文字值

用jquery獲得選擇的checkbox的文字值

<body>
    <input type='checkbox' name='likes' value='music'></input><span>音樂</span>
    <input type='checkbox' name='likes'></input><span>美術</span>
    <input type='checkbox' name='likes'></input><span>資訊科技</span>
    <input type='checkbox' name='likes'></input><span>運動</span>
    <input type='radio' name='other'><span>單選</span></input>
<script src="js/jquery-1.6.4.min.js"></script>
<script>
    var hobbies;
    $("input[name=likes]").change(function(){
        hobbies='';
        //console.log($(this)[0].checked);
        $("input:checked[name=likes]").each(function(index){
            console.log($(this).next('span'));
            if($(this)[0].checked){
                hobbies+=$(this).next('span').text();
                hobbies+=",";
            }
        });
        console.log(hobbies.slice(0,-1));
    });
</script>

若把放裡,用$.fn.children('span')(為空)並不能獲得span。

ps:用jquery可以獲得checkbox的value屬性的值(預設為on, val()),其text(),htm()獲得的值都是空字串。