function uncheck() {
var notTest = document.getElementById("choice_31_3_2");
var Test = document.getElementById("choice_31_3_1");
if (notTest.checked) {
Test.checked = false;
}
if (Test.checked) {
notTest.checked = false;
}
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
I wrote a function to uncheck a checkbox if another one is checked, I am using jQuery to call uncheck() on those specific input.
I am getting the result I want. When I check test then check notTest, Test is being unchecked. BUT when I am pressing Test again, the test checkbox is refusing to check unless I manually uncheck notTest.
I included the code snippet , please can figure out what is wrong ?
The code is running normally on Wordpress but unfortunately not here.
To uncheck a checkbox programmatically in React, we can set the checked prop of the checkbox to a state. We have the checked state that we used to set the checked prop of the checkbox. Then we add a button that calls setChecked to toggle the checked value when we click the button.
Once the checkbox is selected, we are calling prop() function as prop( "checked", true ) to check the checkbox and prop( "checked", false ) to uncheck the checkbox.
To uncheck the checkbox: $("#checkboxid"). removeAttr("checked");
Here you go with a solution
$('input[type="checkbox"]').change(function(){
console.log($(this).is(':checked'));
if($(this).is(':checked')){
$(this).siblings('input[type="checkbox"]').attr('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Hope this will help you.
You can code like this,
HTML:-
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
JQUERY:-
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
Working Demo url
Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With