When radio button 1 is selected print hello 1, when radio button 2 is selected print hello 2. How do I do this?
<form name="form" id="form">
First Class<input name="seat_class" id="a1" type="radio" value="First Class">
Second Clas开发者_运维百科s <input name="seat_class" type="radio" value="Standard Class"
</form>
Try this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#radio1, #radio2").change(function(event) {
if($(this).is(':checked')) {
alert($(this).data("text"));
}
});
});
</script>
<input type="radio" id="radio1" name="test" data-text="hello 1">
<input type="radio" id="radio2" name="test" data-text="hello 2">
First, you need to make some change in your html :
<form name="form" id="form">
First Class
<input name="seat_class" id="a1" type="radio" value="First Class" />
Second Class
<input name="seat_class" type="radio" value="Standard Class" id="a2" />
<!-- Adding id="a2" -->
</form>
And, using jQuery, add an event:
$(function () {
$('#form>input[type=radio]').change(function () {
switch ($(this).attr('id')) {
case 'a1':
alert ('Hello 1');
break;
case 'a2':
alert ('Hello 2');
break;
}
});
});
Here's the result : http://jsfiddle.net/GPwXs/1/
I'm not too sure if you want to check if the radio buttons are pressed? or you want to perform an action when the user turns on one of the radio's, either way:
You can check if either radio is selected by returning only 'selected' buttons:
first = $('#a1:selected');
second = $('#a2:selected');
To perform an action when selecting the radio:
$('#a1').change(function() {
alert('foo');
});
$('#a2').change(function() {
alert('bar');
});
@user760946. I think this is what you are looking for .. jsfiddle.net
精彩评论