2015-11-19 128 views
1

我有一個輸入字段的下列表單。我想確保重點得到重新設置爲相同的輸入後回車/提交表單:提交/輸入後,將焦點保持在同一輸入字段

<form action="https://stackoverflow.com/a/message/new" method="post" id="myform"> 
    <div class="form-group"> 
     <div class="input-group"> 
     <input name="body" id="myField" class="form-control" placeholder="Write message here..." /> <span class="input-group-btn"> 
         <button class="btn btn-default" type="submit" value="{{ _(' Post ') }}">Submit</button> 
         </span> 
     <input type="hidden" name="next" value="{{ request.path }}"> {% module xsrf_form_html() %} 
     </div> 
    </div> 
    </form> 
</div> 

我試圖做以下幾點:

<script> 
    $(function() { 

     //Start check on form submit 
     $('#myform').submit(function(){  

     $('#myField').focus(); 

     }); 

    });  
</script> 

但這並沒有工作

回答

1

submit事件被激發時,表單將提交併刷新/更改頁面,如果其未被阻止,則可以阻止使用表單提交event.preventDefault();

$("#myForm").submit(function(event) { 
    event.preventDefault(); 
}); 

但是,如上所述,這不會像提到的那樣提交表單,除非您正在發出ajax請求,否則不會提供您想要的表單。您可以在頁面加載時將焦點設置在輸入字段上,並且以這種方式將焦點保留在字段上:

$(function() { 
    $('#myField').focus(); 
});