Javascript 选择 onchange='this.form.submit()'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7261305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript select onchange='this.form.submit()'
提问by JonoB
I have a form with a select and a few text inputs. I'd like the form to be submitted when the select is changed. This works fine using the following:
我有一个带有选择和一些文本输入的表单。我希望在更改选择时提交表单。使用以下方法可以正常工作:
onchange="this.form.submit()"
However, if the form also contains a submit button, then the form does not submit when the select is changed. I'm guessing some kind of conflict.
但是,如果表单还包含提交按钮,则在更改选择时表单不会提交。我猜是某种冲突。
What are my options here?
我在这里有哪些选择?
Should I use something like
$(this.form).trigger("submit")
instead?
我应该使用类似的东西
$(this.form).trigger("submit")
吗?
回答by David says reinstate Monica
You should be able to use something similar to:
您应该能够使用类似于以下内容的内容:
$('#selectElementId').change(
function(){
$(this).closest('form').trigger('submit');
/* or:
$('#formElementId').trigger('submit');
or:
$('#formElementId').submit();
*/
});
回答by SLaks
My psychic debugging skills tell me that your submit button is named submit
.
Therefore, form.submit
refers to the button rather than the method.
我的通灵调试技巧告诉我,您的提交按钮名为submit
.
因此,form.submit
指的是按钮而不是方法。
Rename the button to something else so that form.submit
refers to the method again.
将按钮重命名为其他名称,以便form.submit
再次引用该方法。
回答by Tejs
If you're using jQuery, it's as simple as this:
如果您使用的是 jQuery,它就像这样简单:
$('#mySelect').change(function()
{
$('#myForm').submit();
});
回答by Blair Anderson
There are a few ways this can be completed.
有几种方法可以完成。
Elements know which form they belong to, so you don't need to wrap this
in jquery, you can just call this.form
which returns the form element. Then you can call submit()
on a form element to submit it.
元素知道它们属于哪个表单,因此您不需要this
在 jquery 中包装,您只需调用this.form
which 返回表单元素即可。然后你可以调用submit()
一个表单元素来提交它。
$('select').on('change', function(e){
this.form.submit()
});
documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
文档:https: //developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
回答by Wasif Shahjahan
Use :
用 :
<select onchange="myFunction()">
function myFunction() {
document.querySelectorAll("input[type=submit]")[0].click();
}
回答by pimvdb
Bind them using jQuery and make jQuery handle it: http://jsfiddle.net/ZmxpW/.
使用 jQuery 绑定它们并让 jQuery 处理它:http: //jsfiddle.net/ZmxpW/。
$('select').change(function() {
$(this).parents('form').submit();
});