Jimmy
Jimmy

Reputation: 98

How to validate bootstrap radio buttons

I am trying to validate this section of the form but whichever button is selected, option1 returns false. How can I get each radio to have different values when they are active/inactive or alternatively get a value from the button-group?

$(function register(){
$('.err').hide();
$("#submit").click(function() { 
if  ($('#option1').prop("checked", false)){
        $("#fcerr").show();
    }
if  ($('#option1').prop("checked")){
    $("#fcerr").hide();
}
    });
});
<div class="btn-group btn-group-justified btn-group-sm" data-toggle="buttons">
       <label id="lopt1" class="btn btn-primary">
       <input type="radio" name="option1" id="option1" autocomplete="off"> Staff
       </label>
       <label id="lopt2" class="btn btn-primary">
       <input type="radio" name="option2" id="option2" autocomplete="off"> Client
       </label>
</div>
<div><label class="err" id="fcerr">Error Message</label></div>

<input name="register" type="submit" value="Register" class="btn btn-primary btn-lg btn-block" id="submit">
I have also tried getting the values of the radio boxes but they are always "on" regardless of which radio is active.
var client = $("#option2").val();
alert(client);

Upvotes: 2

Views: 2143

Answers (2)

Carlos Valencia
Carlos Valencia

Reputation: 6963

With your code:

if  ($('#option1').prop("checked", false)){
    $("#fcerr").show();
}

You are actually setting the property "checked" to be false, everytime. After that is done the if statement recieves a truthy value so it will execute what's inside the if block.

Try your validation like this instead:

if($('#option1').is(':checked')){
    //...
}

Also, if you want your inputs to actually behave as a group (meaning only one can be checked at a given time) you have to share the same name attribute, you can update your html to:

<label id="lopt1" class="btn btn-primary">
       <input type="radio" name="myOptions" id="option1" autocomplete="off"> Staff
       </label>
       <label id="lopt2" class="btn btn-primary">
       <input type="radio" name="myOptions" id="option2" autocomplete="off"> Client
       </label>

Upvotes: 1

dperish
dperish

Reputation: 1571

A few things:

  1. You didn't include a javascript framework in your code snippet, though your question is tagged with jQuery.
  2. The 4th line if ($('#option1').prop("checked", false)){ is changing the value that you're trying to evaluate.
  3. The option elements should share the same name attribute if you want to treat them as a group that can be validated

Upvotes: 1

Related Questions