2013-10-02 79 views
0

我在一個MVC4網站上工作,我有一個帶搜索文本框的webgrid。我的文本框位於一個表格中,當我按下回車鍵時將會提交。我還有一個綁定到文本框的onkeypress腳本,在3 sek之後,用我輸入的內容更新我的webgrid。運行JavaScript,如果按下按鍵!= ENTER

我的問題是,我只想運行腳本,如果不是按下的最後一個鍵是Enter。

我的代碼如下所示:

    @using (Ajax.BeginForm("Filter", new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "projects" })) 
       { 
        <div class="paddingTextToleft"> 
         Search: 
         <input id="searching" name="searchString" type="text" value="" onkeypress="return keypressed()"> 


         <p class="error">@ViewBag.SearchMessage</p> 

        </div> 
        <br /> 
       } 

和腳本:

var timeoutReference; 

function keypressed() { 
    if (window.event.keyCode == 13) { 
     //Do not run the script! 
     return true; 
    } 
    else { 
     if (timeoutReference) clearTimeout(timeoutReference); 
     timeoutReference = setTimeout(function() { 
      var value = $("#searching").val(); 


      $.ajax({ 
       url: '@Url.Action("Filter", "Project")', 
       contentType: 'application/html; charset=utf-8', 
       type: "GET", 
       dataType: 'html', 
       data: { searchString: value }, 
      }).success(function (result) { 
       $('#projects').html(result); 
      }); 
     }, 3000); 
    } 
}; 

我希望它停止腳本(或不運行它的其餘部分),如果按下的鍵是輸入。

希望任何人都可以幫助我。

感謝

+0

這是什麼問題? – devo

+1

問題是,如果我按Enter鍵,它會調用一個窗體,它將更新視圖。當視圖更新時,文本框被刷新。但是關鍵的聽衆仍然被調用,但是卻對空白文本字段做出了反應。 但我通過使它成爲一個Ajax響應與鍵控監聽器來解決它。 – Moelbeck

回答

1

首先你是不是發送事件的功能。 一些參數調用它e.g:

<input id="searching" name="searchString" type="text" value="" onkeypress="keypressed(e)"> 

然後接受一個函數此事件:

var timeoutReference; 

function keypressed(e) { 
if (e.keyCode == 13) { 
    //Do not run the script! 
    return; 
} 
else { 
    if (timeoutReference) clearTimeout(timeoutReference); 
    timeoutReference = setTimeout(function() { 
     var value = $("#searching").val(); 


     $.ajax({ 
      url: '@Url.Action("Filter", "Project")', 
      contentType: 'application/html; charset=utf-8', 
      type: "GET", 
      dataType: 'html', 
      data: { searchString: value }, 
     }).success(function (result) { 
      $('#projects').html(result); 
     }); 
    }, 3000); 
} 

};