单选按钮值被发送为“开".提交表格后 [英] radio button value being sent as "on" upon form submission

查看:43
本文介绍了单选按钮值被发送为“开".提交表格后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有三个单选按钮选项的表格.我需要将表单数据提交到另一个文件,但是由于某种原因,发送的数据包含所选单选按钮的值为"on",而不是value属性的值.

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.

我尝试通过post()函数手动操作和发送数据,但是由于我需要在提交时重定向页面,因此会导致POST请求和GET请求.此代码的实际目的是要求我将此数据发送到处理该数据并确定将页面重定向到何处的函数.但是,该函数对GET请求有不同的用法,并且在此表单发送GET请求时会出错.这种局限性首先导致了这个问题.

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!

代码:

<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>

推荐答案

您需要使用 value ,而不是 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>

这将在请求中发布 option = 1 option = 2 option = 3 .

This will post option=1, option=2, or option=3 in the request.

小提琴

这篇关于单选按钮值被发送为“开".提交表格后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆