简体   繁体   中英

Finding a radio button on activation in jQuery

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 Class        <input name="seat_class" type="radio" value="Standard Class"
        </form>

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/

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">

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM