I am trying to add a common class gender
for all the inputs. Then i compare if they not checked, and alert empty. How can i properly check if all the buttons are checked?
$( ".btn" ).click(function( event ) { event.preventDefault; if( !$('input .gender').is(":checked") ) alert(" empty"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input class="gender" type="radio" name="answer[1]" value="male"> Male<br> <input class="gender" type="radio" name="answer[1]" value="female"> Female<br> <input class="gender" type="radio" name="answer[1]" value="other"> Other<br> <br><br> <input class="gender" type="radio" name="answer[2]" value="PHP"> PHP<br> <input class="gender" type="radio" name="answer[2]" value="Pyhon"> Python<br> <input class="gender" type="radio" name="answer[2]" value="Java"> Java<br> <input class="btn" type="submit" value="check"> </form>
I'd select the checked radio buttons, and then verify that their length is equal to the number of radio fields:
$( ".btn" ).click(function( event ) { event.preventDefault(); if ($('input[type=radio]:checked').length !== 2) console.log("at least one is empty"); else console.log('pass') });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input class="gender" type="radio" name="answer[1]" value="male"> Male<br> <input class="gender" type="radio" name="answer[1]" value="female"> Female<br> <input class="gender" type="radio" name="answer[1]" value="other"> Other<br> <br><br> <input class="gender" type="radio" name="answer[2]" value="PHP"> PHP<br> <input class="gender" type="radio" name="answer[2]" value="Pyhon"> Python<br> <input class="gender" type="radio" name="answer[2]" value="Java"> Java<br> <input class="btn" type="submit" value="check"> </form>
(preventDefault is a function that needs to be run, not a standalone property to declare.)
To achieve expected , use below option of checking all checkboxes whether checked or not
$( ".btn" ).click(function(event) {
event.preventDefault;
var checkboxList = $('.gender')
var isEmpty = true
$.each(checkboxList,function(i,v){
console.log("is "+v.value+" checked -->"+v.checked)
if(v.checked){
isEmpty = false;
}
})
if(isEmpty){
alert(" empty");
}
});
code sample - https://codepen.io/nagasai/pen/dmzMgo?editors=1011
Explanation:
$('.gender') retrieves all checkboxes and looping it through $.each and checking each field whether checked or not.
Checking flag isEmpty and then alerting based on that
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.