【问题标题】:Unable to submit form even when input is not empty即使输入不为空也无法提交表单
【发布时间】:2021-07-14 15:53:01
【问题描述】:

所以我正在研究一个简单的表单,我正在检查输入是否为空。如果是,那么它应该停止表单提交,但如果不是,那么它将继续提交表单。

现在,当输入字段为空并且我按下提交按钮时,会显示错误消息。但是,如果我在输入字段中输入内容并尝试提交,则 if 块内的代码会再次触发并且表单不会提交。

为什么输入不为空时if块内的代码会再次触发?不是直接跳过if语句直接提交表单吗?

代码如下:

HTML


<div class="name-search" > 

     <form action="/send" method="POST" >

         <input class="search_input" name="name" type="text">
         <button type="submit" class="search_icon"><i class="fas fa-search"></i></button>
            
         <p class="error-msg"></p>  
                    
      </form>

</div>

JS

const form            = $( '.name-search form' );
const formInputVal    = $( '.name-search form .search_input' ).val();
const formErrorMsg    = $( '.name-search form .error-msg' );

$( form ).submit( ( e ) => {

        if ( formInputVal === '' ) {

                $( formErrorMsg ).text( 'Input field can\'t be empty.' );
                return false;

        } 

        return true;

}); 

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    当你把值放到一个变量中时,就是这样,你做一次,当值改变时变量不会改变,所以你需要每次都获取值:

    const form            = $( '.name-search form' );
    const formInput       = $( '.name-search form .search_input' );
    const formErrorMsg    = $( '.name-search form .error-msg' );
    
    $( form ).submit( ( e ) => {
    
            if ( formInput.val() === '' ) {
    
                    $( formErrorMsg ).text( 'Input field can\'t be empty.' );
                    return false;
    
            } 
    
            return true;
    
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 2017-08-27
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2013-06-29
      相关资源
      最近更新 更多