2015-04-26 46 views
0

我在我的导航栏中有一个搜索表单,当用户单击搜索按钮时打开和关闭,使用e.preventDefault()来防止搜索按钮最初提交表单。不幸的是,这个功能似乎阻止了表单提交。jQuery切换搜索表单将不会提交一次event.preventdefault

我已经使用这个jQuery的条件语句,提交表单如果输入字段不为空尝试:

var sInput = $('#s').val(); 

if (sInput == null || sInput == '') { 

    $('#search-button').on('click', function(e) { 

     e.preventDefault(); 
     $('#s').animate({width: 'toggle'}).focus(); 
    }); 
}else{ 

    $('#search-button').on('click', function(e) { 

     return true; 
    }); 
} 

而且,我一直在使用这种尝试:

$('#search-button').on('click', function(e) { 

    if (! $(this).data('clicked')) { 

     e.preventDefault(); 
     $('#s').animate({width: 'toggle'}).focus(); 
    } 

    $(this).data('clicked', true); 
}); 

的搜索表单:

    <div id="search-wrap" class="cf menu-item"> 

         <form class="searchform cf" method="get" action="<?php echo home_url(); ?>/"> 

          <input type="search" id="s" name="s" class="field right"> 

          <div class="search-button-wrap left"> 

           <input type="submit" id="search-button" value=""> 
          </div><!-- End #search-button-wrap --> 
         </form><!-- End .searchform --> 
        </div><!-- End #search-field --> 

该窗体的花式:

#main-nav .menu-item { 
    display: inline-block; 
} 

#s { 
    width:   200px; 
    border:   none; 
    outline:   #FCFCFC; 
    display:   none; 
    position:   relative; 
    border-bottom: solid 1px #C29D52; 
    background-color: #FCFCFC; 
} 

#s.field { 
    font-size:  1.125em; 
    text-align:  center; 
    letter-spacing: 2px; 
} 

.searchform input { 
    display: block; 
} 

#search-button { 
    width:    20px; 
    height:    20px; 
    border:    none; 
    cursor:    pointer; 
    background-color: #FCFCFC; 
    background-image: url(images/search.png); 
    background-repeat: no-repeat; 
    background-position: center; 
} 

#search-wrap { 
    vertical-align: middle; 
} 

我希望搜索表单切换打开,以便用户可以输入他们的搜索关键字,如果他们没有输入任何关键字就关闭,如果他们输入了关键字则提交。我无法弄清楚为什么我现在的代码不能这样工作。

回答

1

将您的输入更改为type =“button”并将ID添加到您的表单中。在JavaScript的else部分中,手动提交表单(即$(“#formId”)。submit())。我也会改变你的逻辑有点...

$('#search-button').on('click', function(e) { 
    var sInput = $('#s').val(); 
    if (sInput == null || sInput == '') { 
     $('#s').animate({width: 'toggle'}).focus(); 
    }else{ 
     $('#formId').submit(); 
    } 
}); 
+0

这工作!谢谢。 – Codette