jQuery with radio button
What's wrong with this code? Why doesn't it show value?
<script>
$(document).ready(function()
{
$('#radio_div').change(function(event){
var value = $("input[@name='rdio']:checked").val();
$('#update_text').html('Radio value:' + value);
});
});
</script>
</head> 开发者_如何学JAVA
<body>
<div id="radio_div">
<input type="radio" name="rdio" value="a" />
<input type="radio" name="rdio" value="b" />
<input type="radio" name="rdio" value="c" />
</div>
<div id="update_text">Please push radio button</div>
Because you're binding to the change event of the radio_div div. A div does not fire a change event, only input elements do that..
Do this instead:
<script>
$(document).ready(function()
{
$('#radio_div input').change(function(event){
var value = $("input[@name='rdio']:checked").val();
$('#update_text').html('Radio value:' + value);
});
});
</script>
</head>
<body>
<div id="radio_div">
<input type="radio" name="rdio" value="a" />
<input type="radio" name="rdio" value="b" />
<input type="radio" name="rdio" value="c" />
</div>
<div id="update_text">Please push radio button</div>
You're adding a change
handler to a <div>
element.
Since <div>
elements never generate change
events, your code doesn't work.
Instead, you should add the change
handler to the input
elements inside the <div>
element, like this:
$('#radio_div :radio').change(...)
(The :radio
selector matches radio inputs)
Try this :
$('#radio_div input:radio').click(function() {
if($(this).is(':checked')) {
$(this).val(); // $(this).attr('value');
}
});
Try this
$(document).ready(function()
{
$("#radio_div input[@name='rdio']").change(function(event){
if ($(this).is(':checked')) {
var value = $(this).val();
$('#update_text').html('Radio value:' + value);
}
});
});
Because you put event handler on change for div, and there is nothing changes there. You need to do:
$(document).ready(function()
{
$("input[@name='rdio']").click(function(event){
if ( $(this).checked)
console.log( $(this).value);
});
});
精彩评论