我想让radio来控制当前我选择的是机动车还是特种车,如下所示:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<input type="radio" id="insuranceType" name="insuranceType" value="0"/>机动车
<input type="radio" id="insuranceType" name="insuranceType" value="1"/>特种车
<script type="text/javascript">
$(document).ready(function ()
{
$("#insuranceType").change(function ()
{
var insuranceTypeVar = $("input[name='insuranceType']:checked").val();
alert(insuranceTypeVar);
});
});
</script>
</body>
</html>
可结果今我很困惑,只有前一个radio选择时才触发change事件,后才发现因为我是使用的 id 作为筛选器!重复id只能选中第一个!
于是加上一个div,如下所示,一切OK
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="insuranceTypeSelect">
<input type="radio" name="insuranceType" value="0"/>机动车
<input type="radio" name="insuranceType" value="1"/>特种车
</div>
<script type="text/javascript">
$(document).ready(function ()
{
$("#insuranceTypeSelect").change(function ()
{
var insuranceTypeVar = $("input[name='insuranceType']:checked").val();
alert(insuranceTypeVar);
});
});
</script>
</body>
</html>
以上还可以优化下,不仅是单击radio圆圈的时候可以选中,单击后边的机动车(特种车)文字的时候,也可以实现radio的选中并触发change事件,如下所示:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="insuranceTypeSelect">
<input type="radio" id="insuranceType1" name="insuranceType" value="0"/><label for="insuranceType1">机动车</label>
<input type="radio" id="insuranceType2" name="insuranceType" value="1"/><label for="insuranceType2">特种车</label>
</div>
<script type="text/javascript">
$(document).ready(function ()
{
$("#insuranceTypeSelect").change(function ()
{
var insuranceTypeVar = $("input[name='insuranceType']:checked").val();
alert(insuranceTypeVar);
});
});
</script>
</body>
</html>