Reputation: 23
How do I use only the selected radio button to show up in the URL? What I have always uses the first radio button regardless of which one is selected:
<form id="urlForm">
<div id="bounds">
<label><input type="radio" name="toggle" id="key"><span>On</span></label>
<label><input type="radio" name="toggle" id="key"><span>Off</span></label>
</div>
</form>
<script>
$(document).ready(function() {
$('#urlForm').submit( function() {
goUrl = '/?constraint=' + $('#key').val() + '+' + $('#key2').val();
window.location = goUrl;
return false; // Prevent the default form behaviour
});
});
</script>
Upvotes: 2
Views: 1901
Reputation: 76003
Your radio inputs should have unique IDs.
<label><input type="radio" name="toggle" id="key1" value="on"><span>On</span></label>
<label><input type="radio" name="toggle" id="key2" value="off"><span>Off</span></label>
And your JavaScript is close but since you are selecting by ID (which doesn't quite work for radio buttons) you need to alter your selectors for the radio inputs:
$(document).ready(function() {
$('#urlForm').submit( function() {
window.location = '/?constraint=' + $('input[name="toggle"]:checked').val();
return false; // Prevent the default form behaviour
});
});
$('input[name="toggle"]:checked')
: This selects a form input with the name attribute set to toggle
and is also checked. This gets the job done but is a pretty inefficient selector.
Here's a jsfiddle: http://jsfiddle.net/jasper/HFBwH/
Upvotes: 1
Reputation: 5316
You have a couple issues in your code.
First: you should use the .preventDefault( ) function to prevent the default event from happening.
Second: you have two elements in your HTML with the same ID. IDs should be unique.
Third: you are missing the value
attributes on your radio buttons
After those are fixed, you can use the following snippet to grab the value of the radio buttons...
$('input:radio[name=bar]:checked').val();
Upvotes: 0
Reputation: 220036
You shouldn't have 2 elements with the same ID. Use this:
HTML:
<form id="urlForm">
<div id="bounds">
<label><input type="radio" name="toggle" id="key1" value="On"><span>On</span></label>
<label><input type="radio" name="toggle" id="key2" value="Off"><span>Off</span></label>
</div>
</form>
JavaScript:
$(document).ready(function() {
$('#urlForm').submit( function() {
goUrl = '/?constraint=' + $('#key1:checked, #key2:checked').val();
window.location = goUrl;
return false; // Prevent the default form behaviour
});
});
Here's the fiddle: http://jsfiddle.net/cgyeY/
P.S. You really don't need that return false;
part, since you're navigating away from the page...
Upvotes: 0