-->

Checking & Unchecking Checkboxes inside a JQuery M

2020-08-25 09:08发布

问题:

I tried this code to achieve what I want to do. It worked when I tried it in my ordinary HTML file, but when I tried it in my JQuery Mobile page, the code did not work well for me. Are there different ways or code to select JQuery Mobile checkboxes?

Here's the code that I tried:

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!">

回答1:

I was not aware that JQuery Mobile's checkboxes need to be refreshed after unchecking/checking them via JQuery or Javascript. Here's the code:

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

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



回答2:

Try this:

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

I removed the FieldName because your function was named SetAllCheckBoxes, just your input fields are the same. You just need tell what's your form and the state of your checkboxes.



回答3:

To toggle / refresh checkboxes in jquery mobile you need to use .prop, rather than .attr.

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