2012-12-02 51 views
7

我試過這段代碼來實現我想要做的事情。當我在普通的HTML文件中嘗試它時,它工作正常,但是當我在我的JQuery Mobile頁面中嘗試它時,代碼對我來說效果不佳。有沒有不同的方式或代碼來選擇JQuery Mobile複選框?檢查並取消選中JQuery Mobile對話框中的複選框

下面是我試過的代碼:

JAVASCRIPT:

<script> 
function SetAllCheckBoxes(FormName, FieldName, CheckValue) 
{ 
    if(!document.forms[FormName]) 
     return; 
    var objCheckBoxes = document.forms[FormName].elements[FieldName]; 
    if(!objCheckBoxes) 
     return; 
    var countCheckBoxes = objCheckBoxes.length; 
    if(!countCheckBoxes) 
     objCheckBoxes.checked = CheckValue; 
    else 
     // set the check value for all check boxes 
     for(var i = 0; i < countCheckBoxes; i++) 
      objCheckBoxes[i].checked = CheckValue; 
} 

HTML

<form method="GET" name="myForm" onsubmit="return false;"> 
<label for="myCheckbox1"> 
    <input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1"> 
    I like Britney Spears 
</label> 
<br> 

<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2"> 
    I like Hillary Duff 
</label> 
<br> 

<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3"> 
    I like Mandy Moore 
</label> 
<br> 

<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="I like them all!"> 
&nbsp;&nbsp; 
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="I don't like any of them!"> 

回答

22

我不知道JQuery Mobile的複選框在取消選中/通過JQuery或Javascript檢查後需要刷新。下面的代碼:

$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh"); 

http://api.jquerymobile.com/checkboxradio/#method-refresh

+0

沒錯。你的答案看起來像我的。 –

+0

是的,但我的代碼唯一的問題是添加'.checkboxradio('刷新')',這可能是最簡單的方式發佈它,所以我添加了我的答案。 – JetPro

+0

好的!好工作。 –

4

試試這個:

function SetAllCheckBoxes(FormName, CheckValue){ 
    $.each($("#"+FormName+" input[type=checkbox]"), function(){ 
     $(this).attr("checked",CheckValue).checkboxradio("refresh"); 
    }); 
} 

我刪除了FieldName,因爲你的函數被命名爲SetAllCheckBoxes,只是你的輸入字段是相同的。你只需要告訴你的表單和你的複選框的狀態。

+0

我已經想通了這件事。我發佈了我的答案,但謝謝你的回答。 – JetPro

0

要切換/在jQuery Mobile的刷新複選框,你需要使用.prop,而不是.attr。

$("input[type='checkbox']").prop("checked",true).checkboxradio("refresh");

相關問題