I have an input type radio button for user to choose one value, like gender. The problem is the value I get only for option one, and when I check, I get warning like [DOM] Found 2 elements with non-unique id
. I need the value so I can passed it to database with ajax.
$('#register').on('click',function(){
var gender=$('#gender').val();
console.log(gender);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get" id="task-form">
<table class="table">
<tr>
<td><input type="radio" name="gender" id="gender" value="male"> Male</td>
<td><input type="radio" name="gender" id="gender" value="female"> Female</td>
</tr>
<tr>
<td><button type="button" class="btn-primary" value="Submit" id="register">Register</button></td>
</tr>
</table>
</form>
Do you know what I need to fix this ?
Thank you
4
Answers
The attribute id must be unique in a document, you can use class instead.
You can use the name attribute along with
:checked
as part of the selector.You cannot have the same
ID
for two different tags.You can modify the
jQuery
function to use the name attribute to pull the value from like belowAny two or more elements on a page cannot have the same ID.
You have given
id="gender"
into input fields.You can give ids as
id="m"
(orid="male"
) andid="f"
(orid="female"
)Then you can user name attribute to get the value of the selected radio button.
In vanilla javascript
var gender = document.querySelector('input[name = "gender"]:checked').value;
You can try this way to achieve it