Gerardo
Gerardo

Reputation: 369

Add validation when specific radio button is selected

I have 3 radio buttons, and I want to throw validation if first radio button is selected_

HTML

<input type="radio" name="editList" id="prov" value="P">
<input type="radio" name="editList" id="user" value="U">
<input type="radio" name="editList" id="suc" value="S">

<select id="lst1"></select>
<select id="lst2"></select>
 <a href="javascript:;" id="event_add" class="btn green"> button </a> 

If I debbug $('input:radio[name="editList"]').val() it always come "P" why it happens?

There is a fiddle of problem

Upvotes: 0

Views: 19

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

The secret with radio buttons is that you have to use the :checked pseudo-selector in conjunction with val(). You're currently always returning P because that is the first option for the group of radio buttons (and therefor the default). You need to check for change by using :checked, like you would for a checkbox.

In order to find the value of the radio button that's currently selected, you're looking for:

$('input:radio[name="editList"]:checked').val()

You also need to actually pass the condition where you check against P into the click of the button itself:

$('#event_add').click(function() {
  if ($('input:radio[name="editList"]:checked').val() === "P") {
    if ($('#lst2').val() === '') {
      alert('You need to select something into lst2.');
      return false;
    }
  }
});

Here's a minimalist example:

$('#event_add').click(function() {
  console.log($('input:radio[name="editList"]:checked').val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="editList" id="prov" value="P">
<input type="radio" name="editList" id="user" value="U">
<input type="radio" name="editList" id="suc" value="S">
<a href="javascript:;" id="event_add" class="btn green"> button </a>

I've also created an updated fiddle demonstrating your code working here.

Hope this helps! :)

Upvotes: 1

Related Questions