单选按钮值在表单提交时作为“开”发送

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

本文关键字:发送 表单提交 单选按钮      更新时间:2023-09-26

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

我尝试通过 post() 函数手动操作和发送数据,但由于我需要在提交时重定向页面,这会导致 POST 请求后跟 GET 请求。此代码的实际目的要求我将此数据发送到处理数据并决定将页面重定向到何处的函数。但是,该函数对 GET 请求有不同的用途,并在此表单发送 GET 请求时给出错误。这种限制首先使这成为一个问题。

有没有办法以某种方式获取要发布的单选按钮的值,而不仅仅是"打开",以便仅从此表单发送一个请求?我了解是否唯一的方法是修改数据发送到的功能。

如果其中有任何不清楚或令人困惑的地方,请发表评论。感谢您的帮助!

法典:

<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=1option=2option=3

小提琴