[英]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. 我需要将表单数据提交到另一个文件,但是由于某些原因,发送的数据包含所选单选按钮的值为“ on”,而不是value属性的值。
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. 我尝试通过post()函数手动操作和发送数据,但是由于我需要在提交时重定向页面,因此会导致POST请求和GET请求。 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. 但是,该函数对GET请求有不同的用法,并且在此表单发送GET请求时会出错。 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
: 您需要使用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>
This will post option=1
, option=2
, or option=3
in the request. 这将在请求中发布option=1
, option=2
或option=3
。
在第一次通过时,我注意到您的表单标签上没有关闭“”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.