Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

radio button value being sent as "on" upon form submission

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>
like image 256
Jawwad Zakaria Avatar asked Oct 24 '13 21:10

Jawwad Zakaria


1 Answers

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

like image 172
Mike Christensen Avatar answered Oct 19 '22 13:10

Mike Christensen