0

I'm seaching a way to do some thing like that in jquery

var my_radio = ("input[name='my_radio']");
my_radio.change(){
    var val = (this":checked").val();
}

How can I do this? thank

1 Answers1

0

You have to edit this:

("input[name='my_radio']");

To this:

$("input[name='my_radio']");

And if you have multiple radio inputs, then you have to make this changes as well:

my_radio.each(function(){
    $(this).on('change', function(){
        if($(this).is(':checked')){
            console.log($(this).val());
        }
    });
});

Example:

var my_radio = $('input[type="radio"]');
my_radio.each(function(){
        $(this).on('change', function(){
            if($(this).is(':checked')){
                $('span').text($(this).val());
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="radio" name="1" value="1" />
  <input type="radio" name="1" value="2" />
  <input type="radio" name="1" value="3" />
  <input type="radio" name="1" value="4" />
</form>

<h1>You selected</h1>
<span></span>
Serghei Leonenco
  • 3,478
  • 2
  • 8
  • 16
  • yes sorry I forget this $ before ("input[name='my_radio']"). – private private Mar 30 '20 at 09:41
  • by the way it's better than to write my_radio.change(function(){ if($(this).is(':checked')){ console.log($(this).val()); } }); what I was searching was how to write in 1 times $(this).is(':checked').val(); – private private Mar 30 '20 at 12:53
  • No it's even more easy as I expected. it's simply $(this).val() because it's the checked who call the change() – private private Mar 30 '20 at 13:19
  • and this would be the other answer myRadio.filter(":checked").val(); I just found the answer now on https://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery – private private Mar 30 '20 at 13:28