简体   繁体   中英

Allow checking to a checkbox even after adding attr(“checked”, false)

I am not sure if a formulated the title correctly but the logic is this.

I have 4 checkboxes, 3 Yes and 1 No . Selecting 3 Yes will uncheck No and selecting No will uncheck Yes .

My jQuery as per below:

var yes = $("input[type=checkbox].yes");

if (yes.length == yes.filter(":checked").length) {
    $("#no").attr("checked", false);
} else if($("#no").is(":checked")) {
    yes.attr("checked", false);
} else {
    // do nothing
}



It works. However, if I checked all Yes , I won't be able to select No . Instead, I need to uncheck 1 Yes to select No . Same thing for No . If I check No , all Yes will be unchecked. However I need to uncheck No to be able to select Yes again.

Will there be a way that I can still select No if all Yes is checked?

Thanks!

UPDATE
Including HTML now

<form id="checkbox-testing" >
<div class="checkform">
    <label>                        
      <input class="yes" type="checkbox" value="Yes, 1" id="yes1"><span>&nbsp;Yes, 1</span> 
    </label>
    <label>                        
      <input class="yes" type="checkbox" value="Yes, 2" id="yes2"><span>&nbsp;Yes, 2</span>
    </label>
    <label>                        
      <input class="yes" type="checkbox" value="Yes, 3" id="yes3"><span>&nbsp;Yes, 3</span>
    </label>
    <label>                        
      <input type="checkbox" value="No" id="no"><span>&nbsp;No</span>
    </label>
</div>
<input type="submit" value="Test" />
</form>

use .prop() to test the checked propert instead of .attr() - the following snippet uses .prop and then use a .change() event - in this case I am just conseol.logging the output but you can change the prop ofr the other checkbox.

EDIT - i just updated my answer to give a radio buton to select on or the other option and a button to clear the checked property on the click.

 $(document).ready(function(){ $("input[type=radio]").change(function(){; console.log("yes: " + $(".yes").prop("checked")); console.log(" no: " + $(".no").prop("checked")); }) $('#clear').click(function(){ $("input[type=radio]").prop('checked',false) }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for ="yes">Yes <input type ="radio" name ="test" id="yes" class="yes" checked value"yes"/></label> <label for ="no">No <input type ="radio" name ="test" id="no" class="no" value = "no"/> <hr/> <button type ="button" name ="test" id="clear" >Clear Value</button> 

var yes = $("input[type=checkbox].yes");

if (yes.length == yes.filter(":checked").length) {
    $("#no").prop("checked", false);
} else if($("#no").is(":checked")) {
    yes.prop("checked", false);
} else {
    // do nothing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM