获取表单帖子外部的单选按钮值


Get radio button value which is outside a form post

我有一个表单,它有一些单选按钮,在这个表单之外

<input type="radio" id="radio1" name="radios" value="radio1" checked>
   <label for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
   <label for="radio2">Debit Card</label>
<form method="post" action='./process.php'>
  <label>name</label>
  <input type="text"/>
  <input type="submit" style="float:right" value="Pay Now"/>
</form>

当我按下paynow按钮时,我想把所选按钮的值传递给这个表单的php(process.php)。但我不想把单选按钮放在表单中。有什么解决方案吗?

您可以在表单中有一个隐藏值,onsubmit将该单选按钮的值放入隐藏值中

<input type="radio" name="test" value="a">a<br>
<input type="radio" name="test" value="b">b
<form>
  <input type="hidden" name="test" id="hidden">
  <submit onClick="transferData">
</form>
<script>
  var transferData = function() {
    var radioVal =$('input:radio[name=test]:checked').val()
    $('#hidden').val(radioVal);
  }
</script>

HTML5支持一个名为"form"的属性。您可以使用它为表单外的控件设置表单,例如:

<input type="radio" id="radio1" name="radios" value="radio1" checked>
<label form="myForm" for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
<label form="myForm" for="radio2">Debit Card</label>
<form id="myForm" method="post" action='./process.php'>
    <label>name</label>
    <input type="text"/>
    <input type="submit" style="float:right" value="Pay Now"/>
</form>

请注意如何将id="myForm"添加到表单中,以及如何将form="myForms"添加到单选按钮中。希望对你有所帮助。

是的,您可以在</body>之前添加对jQuery的引用。然后,使用JQuery,您可以选择选中的单选按钮,如下所示:
var selected = $("input[type='radio']:checked");
if (selected.length > 0) {
    selectedVal = selected.val();
}

selectedVal参数将保存您想要的值。

所选单选按钮的选择应在提交按钮的点击事件上完成。

可以这样做:

$("input[type='submit']").click(function(){    
    // code goes here.    
});

表单上必须有一个onsubmit属性,并且在表单内部,将所选单选按钮值分配给隐藏字段。

像这样:

<form id='myForm' method="post" action='./process.php' onsubmit='getRadioButtonValue()'>
    ...
    <input type="hidden" name="selectedRadioValue" />
</form>
function getRadioButtonValue(){
    var radioValue = $('input[name=radios]:checked', '#myForm').val();
    $('input[name='selectedRadioValue']').val(radioValue);
}

将所有内容放入表单中。如果要发送所有值。将所需的属性添加到标签中。

其他明智的使用jquery

<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password"  id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<ul id="answerswer"></ul>
</body>
<script>
    $("#sub").click(function(event){
        event.preventDefault();
        query = $.post({
            url : 'check_ajax.php',
            data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
        });
        query.done(function(response){
            $('#answer').html(response);
        });
    });
</script>

您所需要做的就是将表单外的选项/输入的值添加到数据

使用此onsubmit事件!

$('input[name=radios]:checked').val()

检查示例