如果输入值为null,我如何使用js或jQuery在提交前用js或jQuery更改输入文本值?
感谢您的帮助。
答案 0 :(得分:33)
使用jQuery,您可以使用.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");
}
});
注意:为确保找到所有元素,应将其放在domready函数中。
答案 1 :(得分:2)
使用纯DOM(无库),您的HTML将类似于:
<form name="foo" action="bar" method="post">
<!-- or method="get" -->
<input name="somefield">
<input type="submit" value="Submit">
</form>
你的脚本看起来像这样:
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';
};