Search code examples
jqueryradio-buttononchange

Check if Radio Button has a value from a list


I'm trying to figure out if there is a way to have when on change check if a radio button has one of the values listed. This is what I have currently:

var stains = $(".stains-container");
var radio_buttons = $("input[name='tmcp_radio_0']");

var $bmaplechecked      = $("input.oak-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains");
var $bmapleactive       = $(".oak-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li");
var $bmapleactivehide   = $(".oak-stains-div, .cherry-stains-div, .qswo-stains-div, .h-maple-stains-div, .hickory-stains-div");


var $bmapleval = $( /^Brown Maple_\d$/.test($(this).val()) );
var $wmapleval = $( /^Wormy Maple_\d$/.test($(this).val()) );
radio_buttons.on('change',function(){
    if ($bmapleval, $wmapleval) {
        stains.show();
        $(".b-maple-stains-div").show();
        $bmaplechecked.prop('checked', false);
        $bmapleactive.removeClass( "tc-active" );
    } else {
        $(".b-maple-stains-div").hide();
    }
});

Under the if condition I'm trying to have it check if it has one of the variables listed. I've tried it as it is and as if ($bmapleval || $wmapleval) but no success. I'm not the greatest with JQuery so any guidance is greatly appreciated.


Solution

  • Don't stick booleans in a jQuery object. And you need to evaluate the value of the selected radio in the event handler.

    radio_buttons.on('change', function(e) {
      var brownMapleRegExp = /^Brown Maple_\d$/;
      var wormyMapleRegExp = /^Wormy Maple_\d$/;
    
      if (brownMapleRegExp.test(e.target.value) || wormyMapleRegExp.test(e.target.value)) {
        stains.show();
        $(".b-maple-stains-div").show();
        $bmaplechecked.prop('checked', false);
        $bmapleactive.removeClass("tc-active");
      } else {
        $(".b-maple-stains-div").hide();
      }
    });