说我有:
<form method="get" action="something.php">
<input type="text" name="name" />
</form>
<input type="submit" />
我如何在表单外提交那个提交按钮,我认为在HTML5中有一个提交的动作属性,但我不确定这是否完全跨浏览器,如果不是的话,有没有办法这样做?
说我有:
<form method="get" action="something.php">
<input type="text" name="name" />
</form>
<input type="submit" />
我如何在表单外提交那个提交按钮,我认为在HTML5中有一个提交的动作属性,但我不确定这是否完全跨浏览器,如果不是的话,有没有办法这样做?
当前回答
类似于这里的另一个解决方案,只是稍加修改:
<form method="METHOD" id="FORMID">
<!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>
https://www.w3schools.com/tags/att_form.asp
其他回答
试试这个:
<input type="submit" onclick="document.forms[0].submit();" />
尽管我建议在表单中添加一个id,并通过它来访问,而不是document.forms[index]。
这是一个相当可靠的解决方案,它包含了迄今为止最好的想法,也包括了我对奥弗林强调的问题的解决方案。不使用javascript。
如果你关心IE的向后兼容性(甚至Edge 13),你不能使用form="your-form"属性。
使用一个标准的提交输入,并在表单外添加一个标签:
<form id="your-form">
<input type="submit" id="your-form-submit" style="display: none;">
</form>
注意使用display: none;。这是故意的。使用bootstrap的.hidden类与jQuery的.show()和.hide()冲突,并且在bootstrap 4中已弃用。
现在只需为你的提交添加一个标签,(风格为bootstrap):
<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
Submit
</label>
与其他解决方案不同,我还使用tabindex -设置为0 -这意味着我们现在与键盘选项卡兼容。添加role="button"属性为它提供了CSS样式的游标:指针。瞧。(看这把小提琴)。
类似于这里的另一个解决方案,只是稍加修改:
<form method="METHOD" id="FORMID">
<!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>
https://www.w3schools.com/tags/att_form.asp
也许这可以工作,但我不知道这是否是有效的HTML。
<form method="get" action="something.php">
<input type="text" name="name" />
<input id="submitButton" type="submit" class="hide-submit" />
</form>
<label for="submitButton">Submit</label>
这工作很完美!;)
这可以使用Ajax和我所说的“表单镜像元素”来完成。为了发送带有外部元素的表单,您可以创建一个假表单。 不需要前面的表单。
<!-- This will do the trick -->
<div >
<input id="mirror_element" type="text" name="your_input_name">
<input type="button" value="Send Form">
</div>
ajax代码是这样的:
<script>
ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");
function ajax_form_mirror(form, file, element, method) {
$(document).ready(function() {
// Ajax
$(form).change(function() { // catch the forms submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: method, // GET or POST
url: file, // the file to call
success: function (response) { // on success..
$(element).html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
}
</script>
如果您想在另一个表单中发送一些数据而不提交父表单,这是非常有用的。
这段代码可能可以根据需要进行调整/优化。它工作得很完美!!;) 如果你想要一个这样的选择选项框也可以:
<div>
<select id="mirror_element" name="your_input_name">
<option id="1" value="1">A</option>
<option id="2" value="2">B</option>
<option id="3" value="3">C</option>
<option id="4" value="4">D</option>
</select>
</div>
我希望它能像帮助我一样帮助别人。;)