2013-05-06 104 views
0

我想在使用jQuery和javascript單擊按鈕後驗證表單的輸入值。如何驗證表單的輸入值

現在,如果我輸入一個值作爲輸入,然後單擊提交輸入字段,按鈕就會消失。任何想法我在這裏錯了嗎?

HTML文件...

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <link/> 
     <script type='text/javascript' src='script.js'></script> 
    </head> 
    <body> 
      <form> 
       <input type="text" id='input_1'> 
       <input type="submit" value="Send" id="send"> 
      </form> 
    </body> 
</html> 

腳本文件...

$(document).ready(function() { 
    $('.send').click(function() { 
     validateInput(document.getElementById('#input_1')); 
     function validateInput(inputValue){ 
      if (inputValue === 3) { 
      alert("Element cannot be equal to 3"); 
      } 
     } 
    }); 
}); 
+0

[最佳的jQuery表單插件。輕鬆驗證任何使用「beforeSubmit」選項](http://malsup.com/jquery/form/#ajaxForm) – SpYk3HH 2013-05-06 15:10:38

+0

'click(function(event){event.preventDefault();'將停止執行表單提交 – Eraden 2013-05-06 15:10:58

+0

另外不要使用'click()'。請使用'on('click',...' – Eraden 2013-05-06 15:11:50

回答

1
$(document).ready(function() { 
    $('#send').live('click',function() { //Because send is the id of your button 
     if(validateInput(document.getElementById('#input_1'))){ 
      alert("Element cannot be equal to 3"); 
      return false; 
     } 
     else{ 
      //Do something else 
     } 
     function validateInput(inputValue){ 
      if (inputValue == 3) { 
      return false;//Will prevent further actions 
      } 
     } 
    }); 
}); 
+0

我看到我正在使用。而不是#發送按鈕。我還包括'返回false; //將阻止進一步的行動',如你所建議的。點擊發送後,輸入和按鈕仍然消失。任何額外的想法? – 2013-05-06 15:15:03

+2

使用'.on()'或'.delegate()'而不是'.live()'。現場已棄用! – cortex 2013-05-06 15:16:06

+0

返回false必須在click函數中,而不是'validateInput()'。 – 2013-05-06 15:17:03

0
  1. $('.send').click(function() { 應該是$("#send").click(function() {。 注意哈希符號而不是點(。),如果選擇器是類,則使用點,而如果選擇器是ID,則使用#。

2.You應該移動驗證功能外$(document).ready(function() ..希望幫助

0

謝謝大家的響應。不幸的是,我無法使用您的建議來實現它。我決定使用jQuery來獲取元素,並將附加消息而不是使用alert。這是一種不同的方法,但最終工作。

HTML ...

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <link/> 
     <script type="text/javascript" src="script.js"></script> 
    </head> 
    <body> 
      <form> 
       <input type="text" name="input"/> 

      </form> 
      <button id="send">Send</button> 
      <div class="error"> 
      </div> 
    </body> 
</html> 

腳本...

$(document).ready(function() { 
    $('#send').click(function(){ 
    var toValidate = $('input[name=input]').val(); 
    if (toValidate == 3) { 
    jQuery('.message').html(''); 
     $('.error').append('<div class="message">' + toValidate + " is invalid" + '</div>'); 
    } 
    else { 
     jQuery('.message').html(''); 
     $('.error').append('<div class="message">' + toValidate + " is valid" + '</div>'); 
     } 

    }); 
});