16

I have two radio buttons with the same name but different values. I have to check before I submit my form that value selected id correct otherwise give message to user.

Here is my HTML code:

<td> <label> <span><input type="radio" name="directed" value="1" id="directed_yes"></span> <span>Yes</span> </label><br> <label> <span><input type="radio" name="directed" value="0" id="directed_no"></span> <span>No</span> </label> </td> 

Here is my JQuery that i tried to use:

var directed = $('input[name=directed]').each(function(){ alert($(this).val()) }); 

This code gave me all values for elements with the same name, I just need selected value. After that I have to check if that value is valid before submitting the form. If anyone know how to get just selected value please let me know. Thanks.

0

1 Answer 1

4

You can just use the :checked selector and val(): like this:

var directed = $('input[name=directed]:checked').val(); 

$('button').click(function() { var directed = $('input[name=directed]:checked').val(); alert(directed); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <span><input type="radio" name="directed" value="1" id="directed_yes"></span> <span>Yes</span> </label> <br> <label> <span><input type="radio" name="directed" value="0" id="directed_no"></span> <span>No</span> </label> <br /><br /> <button>Get value</button>

Sign up to request clarification or add additional context in comments.

2 Comments

That's exactly what I was looking for. Without ':checked' I was getting same value no matter what was checked. Thanks a lot!
No problem, glad to help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.