I have a form with three radio button options. I need to submit the form data to another file, but for some reason the data sent contains the value of the selected radio button as "on" as opposed to the value of the value attribute.
I tried manually manipulating and sending the data via the post() function but since I need to redirect the page upon submission, that results in a POST request followed by a GET request. The actual purpose of this code requires me to send this data to a function which handles the data and decides where to redirect the page. However, that function has different uses for GET requests and gives errors when this form sends a GET request. That limitation is what is making this a problem in the first place.
Is there a way to somehow get the value of the radio button to be posted instead of just "on" such that there is only one request sent from this form? I understand if the only way is to modify the function that the data is sent to.
Please comment if any of this is unclear or confusing. Thank you for your help!
Code:
<form name="send-form" class="send-form" method="POST" action="somefunction>
<input type="radio" name="option" id="1" val="1">
<input type="radio" name="option" id="2" val="2">
<input type="radio" name="option" id="3" val="3">
</form>
<script>
$(".send-form").submit(function(e){
e.preventDefault();
// get selected value
var selected = $("input[type='radio'][name='option']:checked");
// check if an option was selected
if (selected.length > 0) {
selectedValue = selected.attr("id");
$.post('somefile', {"option" : selectedValue}, function() {
window.location.href = "somefile";
});
}
} else {
alert("Please select an option");
}
});
</script>
You need to use value
, instead of val
:
<form name="send-form" class="send-form" method="POST" action="somefunction">
<input type="radio" name="option" id="1" value="1" />
<input type="radio" name="option" id="2" value="2" />
<input type="radio" name="option" id="3" value="3" />
</form>
This will post option=1
, option=2
, or option=3
in the request.
Fiddle
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