radio button value being sent as “on” upon form submission

左心房为你撑大大i 提交于 2021-01-27 06:24:26

问题


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>

回答1:


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




回答2:


On first pass I noticed you don't have a closing " on your form tag.



来源:https://stackoverflow.com/questions/19577484/radio-button-value-being-sent-as-on-upon-form-submission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!