2013-09-01 117 views
0

http://jsfiddle.net/nqCFL/按鈕點擊使用jQuery取消形式和重定向頁面

我試圖檢查輸入的值,如果它是空的,重定向的頁面,如果不爲空,重定向到另一頁。它沒有任何價值,也不代表我實際想要做的事情,它只是一個實驗。這個實驗應該幫助我實現目標,即檢查輸入,如果它是空的,請提交表單。如果它不是空的,請取消表單並重定向到另一頁。我正在試用Botcha,這在想法上是相似的。問題是頁面只是不斷刷新按鈕點擊,並不會根據我上面的測試重定向。

實驗我是:

<form action="" method="post"> 
    <input type="text" placeholder="issue" class="issue-input" /> 
    <button class="submit button" type="submit">Send</button> 
</form> 

$(".submit").click(function(){ 
      if($(".issue-input").val().length == 0) { 
       window.location.href = "http://www.google.com"; 
      } else { 
       window.location.href = "http://www.yahoo.com"; 
      }; 
}); 

回答

2

因爲你的按鈕提交按鈕,這樣你的點擊會提交表單,嘗試的jQuery使用的preventDefault方法。

$(".submit").click(function (e) { 
    e.preventDefault(); 
    if ($(".issue-input").val().length == 0) { 
     window.location.href = "http://www.google.com"; 
    } else { 
     window.location.href = "http://www.yahoo.com"; 
    }; 
}); 

嘗試小提琴:http://jsfiddle.net/nqCFL/2/,我修改了鏈接到錯誤的URL,所以你可以看到頁面重定向。

+0

謝謝。我使用$(「form」)。submit();在原來的代碼,但我忘了preventDefault ...愚蠢的。 –

1

嘗試:

$(".submit").click(function(){ 
     if($(".issue-input").val() == ''){ 
      window.location.href = "http://www.google.com"; 
     } else { 
      window.location.href = "http://www.yahoo.com"; 
     }; 
}); 
相關問題