1

I've created a set of radio buttons using bootstrap and now I need to do a check to determine which button is active (To determine what string to use later in my project).

Currently I'm just trying to get an alert to appear for debugging:

$(document).ready(function() {

    var rg_eu = document.getElementById('option1');

    $('#searchplayer1').keypress(function(e) {
    var keycode = (e.keyCode ? e.keyCode : e.which);
        if(keycode == '13') { 
            if($(document.getElementById('option1')).hasClass('active')) {
                alert(rg_eu);
            }
        }
    });
});

However my alert doesn't appear. Also tried checking with 'focus' and 'btn btn-secondary active' - but nothing seemed to work. Do I have to do this in some unconventional manner because it's done through bootstrap?

  • Possible duplicate of [Find out if radio button is checked with JQuery?](https://stackoverflow.com/questions/2272507/find-out-if-radio-button-is-checked-with-jquery) – S. Dev Apr 24 '18 at 09:52
  • Yes, bootstrap applies the `active` class to the label, not the button itself. – paul Apr 24 '18 at 09:52
  • in jQuery... if ( $('#option1') **.is(':checked')** ) – Roy Bogado Apr 24 '18 at 09:55

2 Answers2

0

Bootstrap applies the active class to the label, not the button itself.

Here is one way to check the button:

$(document).ready(function() {
    $('#searchplayer1').keypress(function(e) {
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if(keycode == '13') { 
            if($('#option1').is(':checked')) {
                alert('option checked');
            }
        }
    });
});
paul
  • 21,653
  • 1
  • 53
  • 54
0

there is a selector in jquery which gives you the checked radio button in a particular radio group:

if(jQuery("input[name="option1"]:checked")) { alert('radio is active'); }

other methods ,

1. $('#option1').is(':checked') 
2. $('#option1').prop('checked')

Refer the following link https://api.jquery.com/checked-selector/