Javascript 如果值为空,则在提交前使用js或jQuery更改输入文本值

Javascript 如果值为空,则在提交前使用js或jQuery更改输入文本值,javascript,jquery,Javascript,Jquery,如果输入值为空,那么在提交之前如何使用js或jQuery更改输入文本值 感谢您的帮助。使用,您可以使用方法将回调绑定到提交事件 注意:为了确保所有元素都可以找到,它应该放在一个函数中。对于普通DOM(无库),您的HTML看起来像: <form name="foo" action="bar" method="post"> <!-- or method="get" --> <input name="somefield"> <input

如果输入值为空,那么在提交之前如何使用js或jQuery更改输入文本值

感谢您的帮助。

使用,您可以使用方法将回调绑定到提交事件

注意:为了确保所有元素都可以找到,它应该放在一个函数中。

对于普通DOM(无库),您的HTML看起来像:

<form name="foo" action="bar" method="post">
    <!-- or method="get" -->
    <input name="somefield">
    <input type="submit" value="Submit">
</form>

你能解释一下通知:更多信息吗?您是说需要将整个内容包装到:$(document.ready(function(){YOURCODEHERE})@不,因为这与问题无关。整个过程在提供的链接中进行了彻底的解释。我认为您指的是
form.elements.somefield
,而不是
form.elements.something
<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';
    };