如何验证表单的输入值
我想在使用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");
}
}
});
});
$(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
}
}
});
});
我看到我正在使用。而不是#发送按钮。我还包括'返回false; //将阻止进一步的行动',如你所建议的。点击发送后,输入和按钮仍然消失。任何额外的想法? – 2013-05-06 15:15:03
使用'.on()'或'.delegate()'而不是'.live()'。现场已弃用! – cortex 2013-05-06 15:16:06
返回false必须在click函数中,而不是'validateInput()'。 – 2013-05-06 15:17:03
- 这
$('.send').click(function() {
应该是$("#send").click(function() {
。 注意哈希符号而不是点(。),如果选择器是类,则使用点,而如果选择器是ID,则使用#。
2.You应该移动验证功能外$(document).ready(function()
..希望帮助
谢谢大家的响应。不幸的是,我无法使用您的建议来实现它。我决定使用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>');
}
});
});
[最佳的jQuery表单插件。轻松验证任何使用“beforeSubmit”选项](http://malsup.com/jquery/form/#ajaxForm) – SpYk3HH 2013-05-06 15:10:38
'click(function(event){event.preventDefault();'将停止执行表单提交 – Eraden 2013-05-06 15:10:58
另外不要使用'click()'。请使用'on('click',...' – Eraden 2013-05-06 15:11:50