Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get just selected value from the group of elements with the same name? [duplicate]

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.

like image 407
espresso_coffee Avatar asked Jan 14 '16 17:01

espresso_coffee


1 Answers

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>
like image 62
Rory McCrossan Avatar answered Oct 14 '22 15:10

Rory McCrossan