[英]change input text value with js or jQuery before submit if value is null
How can I with js or jQuery change input text value with js or jQuery before submit if the input value is null ? 如果输入值为null,如何使用js或jQuery在提交之前使用js或jQuery更改输入文本值?
Thanks for help. 感谢帮助。
With jQuery , you can bind a callback to the submit event with the .submit()
method. 使用jQuery ,您可以使用
.submit()
方法将回调绑定到submit事件。
$("form").submit(function(){
// Let's find the input to check
var $input = $(this).find("input[name=whatever]");
if (!$input.val()) {
// Value is falsey (i.e. null), lets set a new one
$input.val("whatever you want");
}
});
Notice: To ensure that all the elements can be found it should be placed in a domready function. 注意:为确保找到所有元素,应将其置于domready函数中。
With plain DOM (no library), your HTML will look something like: 使用纯DOM(无库),您的HTML将如下所示:
<form name="foo" action="bar" method="post">
<!-- or method="get" -->
<input name="somefield">
<input type="submit" value="Submit">
</form>
And your script will look something like this: 你的脚本看起来像这样:
var form = document.forms.foo;
if (form && form.elements.something)
// I use onsubmit here for brevity. Really, you want to use a
// function that uses form.attachEvent or form.addEventListener
// based on feature detection.
form.onsubmit = function() {
// if (form.elements.foo.value.trim()) is preferable but trim()
// is not available everywhere. Note that jQuery has $.trim(),
// and most general purpose libraries include a trim(s)
// function.
if (form.elements.something.value.match(/^\s*$/)))
form.elements.something.value = 'DEFAULT VALUE';
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.