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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With