JQuery sample code that determines if radio is selected and gets the selected value


Other functions to operate on radio will be added later. Go straight to the code and don’t forget to reference the JQuery package

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery radio</title>
<script type="text/javascript" language="javascript" src="JavaScript/jquery-1.6.1.min.js" ></script>
<script type="text/javascript" language="javascript">

$(function(){
$("#btnSubmit").click(function(){
var val=$('input:radio[name="sex"]:checked').val();
if(val==null){
alert(" Nothing selected !");
return false;
}
else{
alert(val);
}
var list= $('input:radio[name="list"]:checked').val();
if(list==null){
alert(" Please select one !");
return false;
}
else{
alert(list);
}
});
});
</script>
</head>

<body>
<form id="form1" >
<input type="radio" name="sex" value=" male " /> male
<input type="radio" name="sex" value=" female " /> female
<br />
<input type="radio" name="list" value=" Very satisfied with " /> Very satisfied with
<input type="radio" name="list" value=" Satisfied with the " /> Satisfied with the
<input type="radio" name="list" value=" Not satisfied with " /> Not satisfied with
<input type="radio" name="list" value=" Very poor " /> Very poor
<br />
<input type="submit" value="submit" id="btnSubmit" />
</form>
</body>
</html>

The net friend comment on: var boolCheck = $(’ input: radio [name = “sex”] ”), is (” : checked ”); It’s better. It’s simpler

Is () detects a collection of matching elements based on a selector, element, or jQuery object, and returns true if at least one of those elements matches a given parameter.

If you save post-garble, use notepad++ here.