1. 程式人生 > >IE,firefox下jquery獲取一組checkbox選中值的問題

IE,firefox下jquery獲取一組checkbox選中值的問題

HTML 程式碼:

<form>
<input type="checkbox" name="newsletter" checked="checked" value="Daily" />
<input type="checkbox" name="newsletter" value="Weekly" />
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
</form>

jQuery 程式碼:

$("input:checked")

結果:

[ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />, <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ]

var check = $("input:checked"); //得到所有被選中的checkbox
   var actor_config;              //定義變數
   check.each(function(i){         //迴圈拼裝被選中項的值
    actor_config = actor+','+$(this).val();
    });
   alert(actor_config.substr(9)+',');

通過以下js程式碼去獲取選中項的值,在IE7中可以正確取得選中項的值,但在IE8中卻得不到選中項的值,同樣在Firefox 3.5.3下也得不到值,但公司同事在Firefox其他較低版本下能正確得到值,IE6下也沒有問題,⊙﹏⊙b汗

$('#permissionList-body input[name="checkboxes"][checked]').each(function(i){ alert($(this).val());});

      但是把技術程式碼修改為:

$('#permissionList-body input[name="checkboxes"]').each(function(i){ if(this.checked)alert($(this).val());});===========================================================================$('#permissionList-body input[name="checkboxes"][checked]')$('#permissionList-body input[name="checkboxes"][checked='checked']')這兩種寫法支援 IE$('#permissionList-body input[name="checkboxes"][checked='true']')這種支援firefox沒有找到好的解決方法,只有加 if(this.checked)判斷了 jquery radio取值,checkbox取值,select取值,radio選中,checkbox選中,select選中,及其相關

獲取一組radio被選中項的值
var item = $('input[@name=items][@checked]').val();
獲取select被選中項的文字
var item = $("select[@name=items] option[@selected]").text();
select下拉框的第二個元素為當前選中值
$('#select_id')[0].selectedIndex = 1;
radio單選組的第二個元素為當前選中值
$('input[@name=items]').get(1).checked = true;

獲取值:

文字框,文字區域:$("#txt").attr("value");
多選框checkbox:$("#checkbox_id").attr("value");
單選組radio:   $("input[@type=radio][@checked]").val();
下拉框select: $('#sel').val();

控制表單元素:
文字框,文字區域:$("#txt").attr("value",'');//清空內容
                 $("#txt").attr("value",'11');//填充內容

多選框checkbox: $("#chk1").attr("checked",'');//不打勾
                 $("#chk2").attr("checked",true);//打勾
                 if($("#chk1").attr('checked')==undefined) //判斷是否已經打勾

單選組radio:    $("input[@type=radio]").attr("checked",'2');//設定value=2的專案為當前選中項
下拉框select:   $("#sel").attr("value",'-sel3');//設定value=-sel3的專案為當前選中項
                $("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel")//新增下拉框的option
                $("#sel").empty();//清空下拉框

// 清空所有複選框選項
      $(":checkbox").attr("checked","");

===========================================================以Name獲得值的方法(我用的方法)var str="";
       $("input[name='newsletter']").each(function(){
           if(this.checked) str+=$(this).val()+",";       
       })
        alert(str);