Reputation: 914
Here's the HTML:
<form>
<div class="form-group">
<div class="checkbox-detailed male_input">
<input type="radio" name="gender" id="male" value="male">
<label for="male">
<span class="checkbox-detailed-tbl">
<span class="checkbox-detailed-cell">
<span class="checkbox-detailed-title">Male</span>
</span>
</span>
</label>
</div>
<div class="checkbox-detailed female_input" style="margin-left: 25px!important">
<input type="radio" name="gender" id="female" value="female">
<label for="female">
<span class="checkbox-detailed-tbl">
<span class="checkbox-detailed-cell">
<span class="checkbox-detailed-title">Female</span>
</span>
</span>
</label>
</div>
</div>
<button type="submit" class="btn btn-rounded" id="user_submit">Sign In</button>
</form>
And Here's the javascript section:
var user_gender = $("input[name='gender']:checked");
var user_submit = $('#user_submit');
user_submit.click(function(){
console.log(user_gender.val())
});
I also tried var user_gender = $("input[name=gender]:checked");
(without quotes between gender) and var user_gender = $("input:radio[name='gender']:checked");
, it still didn't work. It's logging undefined for user_gender variable, am I doing anything wrong?
Upvotes: 1
Views: 50
Reputation: 337560
You are getting the checked radio when the page loads. You instead need to get it when the button is clicked.
To do that move the selector inside the event handler:
$('form').submit(function(e) {
e.preventDefault(); // stop the form submission. Remove once you've finished testing
var $user_gender = $('input[name="gender"]:checked');
console.log($user_gender.val())
});
A couple of things to note here. Firstly, the naming convention for variables which contain jQuery objects is to prefix their names with a $
as I've done in the above example.
Secondly, when dealing with forms, hook to the submit
event of the form
itself, not the click
event of the submit
button. This is for accessibility reasons. It's also better semantically.
Upvotes: 3
Reputation: 36309
You want to move the query within the function like this:
var user_submit = $('#user_submit');
user_submit.click(function(){
var user_gender = $("input[name='gender']:checked");
console.log(user_gender.val())
});
What you are doing is getting the checked values before you are submitting, which is probably nothing at the time of loading the page.
Upvotes: 1