I would like to check to see if a box is checked using jquery.
My aim is to prevent the form from hiding if no option is selected.
$("#submit").click(function(){
var opt = $('input[name=value]:checked').attr('value');
if(opt!='undefined'){
$.ajax({
type: "POST",
url: url,
data: 'option='+opt,
cache: false,
success: function(html)
{
alert(opt);
}
});
}
return false;
});
html
<form id="form" method="post" action="">
<input type="radio" name="value" value="1" />1<br>
<input type="radio" name="value" value="2" />2<br>
<input type="radio" name="value" value="3" />3<br>
<input type="radio" name="value" value="4" />3<br>
<input id="submit" type="submit" value="submit"/>
</form>
I suggest just checking
$('input[name=value]:checked').lengthbefore doing anything else. ) If no element was checked, it will be equal to 0. In other words, replace…with
Your original code, though, is pretty close, with just a single mistake: you should compare
opttoundefined(a variable), not to'undefined'(a string).The
opt != 'undefined'will actually always evaluate tofalse, as no radio button in your HTML has value'undefined'. Again, consider the difference betweenfalseand'false'– the latter is actually a truthy value (though not equal totrue);