1. 程式人生 > >jquery如何根據多選框name來獲得選中的值。

jquery如何根據多選框name來獲得選中的值。

comm lin input this func jpg 代碼實現 title ali

根據多選框name來獲得選中的值可用如下 jquery代碼實現

1 2 3 $("input:checkbox[name=‘test‘]:checked").each(function() { // 遍歷name=test的多選框 $(this).val(); // 每一個被選中項的值 });

實例演示:給出兩組多選框,點擊按鈕後分別獲得兩組中被選擇的項目

示例代碼如下

  1. 創建Html元素

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <div class="box"> <span>請輸入用戶名,限定字母、數字或下劃線的組合:</
    span> <div class="content"> <span>水果:</span> <input type="checkbox" name="fruit" value="梨子"/>梨子 <input type="checkbox" name="fruit" value="李子"/>李子 <input type="checkbox" name="fruit" value="栗子"/>栗子 <input type="checkbox"
    name="fruit" value="荔枝"/>荔枝 <span>蔬菜:</span> <input type="checkbox" name="vegetable" value="青菜"/>青菜 <input type="checkbox" name="vegetable" value="蘿蔔"/>蘿蔔 <input type="checkbox" name="vegetable" value="土豆"/>土豆 <input type="checkbox"
    name="vegetable" value="茄子"/>茄子 </div> <input type="button" value="提交"> </div>
  2. 設置css樣式

    1 2 3 4 5 div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;} div.box span{color:#999;font-style:italic;} div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;} input[type=‘checkbox‘]{margin:5px;} input[type=‘button‘]{height:30px;margin:10px;padding:5px 10px;}
  3. 編寫jquery代碼

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $(function(){ // 設置屬性值 $("input:button").click(function() { var fruit = ""; var vegetable = ""; $("input:checkbox[name=‘fruit‘]:checked").each(function() { fruit += $(this).val() + " "; }); $("input:checkbox[name=‘vegetable‘]:checked").each(function() { vegetable += $(this).val() + " "; }); alert("已選擇水果:"+fruit+",已選擇蔬菜:"+vegetable); }); })
  4. 觀察效果

    技術分享圖片

jquery如何根據多選框name來獲得選中的值。