yaylitzis yaylitzis - 1 month ago 5
Javascript Question

check for empty radio input

I want to check if the user selects a radio button. I have coded this:

HTML

<form action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
//etc
<button type="submit" class="myButton" onclick="sendSuccess()">Submit</button>
</form>


JS

function sendSuccess(){

var len = document.formRate.ratingInput1.length;
var flag;

for(i=0; i<len; i++){
if (document.formRate.ratingInput[i].checked){
flag = true;
}
else{
flag = false;
break;
}
}

if(flag === false){
console.log('noooooo');
return false;
}else{
console.log('yesssss');
}
}


But its not working.

Answer

Working demo http://jsfiddle.net/cXPYQ/

Hope this fit your needs :) Code

  $("form").submit(function () {
    var flag = true;
    $(':radio').each(function () {
        name = $(this).attr('name');
        if (flag && !$(':radio[name="' + name + '"]:checked').length) {
            alert(name + ' group not checked');
            flag = false;
        }
    });
    return flag;
});
Comments