2013-02-01 43 views
0

当我提交与空字段的形式我得到对话框成功消息。相反,我想在对话框中显示错误信息。请帮我找到解决方案。jQuery的空场验证

我的HTML代码:

<form id="booking" action="" method="post"> 
    First Name:<input type="text" id="firstName" name="firstName" maxlength="30" /><br/> 
    Last Name:<input type="text" id="lastName" name="lastName" maxlength="30"/><br/> 
    Contact:<input type="text" id="contact" name="contact" maxlength="15"/><br/> 
    Email: <input type="text" id="email" name="email" maxlength="30"/><br/> 
    <input id="save" type="button" value="Save" /> 
    </form> 
    <div id="dialog"></div> 

jQuery代码:

$('#save').click(function(){ 
    if(('#firstName').length==0 && ('#lastName').length==0 && ('#contact').length==0 && ('#email').length==0){ 
    $('#dialog').attr('title','Error').text('All fields are required').dialog(); 
    }else{ 
    $('#dialog').attr('title','Success').text('Success').dialog(); 
    } 
    }); 
+0

我会去了解一下'jQuery的validate'插件。 –

回答

1

('#firstName') - >如果你正在使用jQuery,这应该是$('#firstName')

这个条件将始终返回false: ('#firstName').length==0 && ('#lastName').length==0 && ('#contact').length==0 && ('#email').length==0

得到一个输入文本类型的值长度:

$('#firstName).val().length 

更新:

试试这个:

$('#save').click(function(){ 
    if($('#firstName').val().length==0 && $('#lastName').val().length==0 && $('#contact').val().length==0 && $('#email').val().length==0){ 
    $('#dialog').text('All fields are required').dialog({title:'Error'}); 
    } else{ 
    $('#dialog').text('Success').dialog({title:'Success'}); 
    } 
}); 
+0

这是正常的,但标题仍然是相同的“错误”我希望将它更改为“成功” – user1897595

+0

你的代码是完美的。 。我看到标题'成功',逻辑很棒'val()。length == 0' – user1897595

0

试试这个,

$('#save').click(function(){ 
    if($('#firstName').val()=="" || $('#lastName').val()=="" || $('#contact').val()=="" || $('#email').val()==""){ 
    $('#dialog').attr('title','Error').text('All fields are required').dialog(); 
    }else{ 
    $('#dialog').attr('title','Success').text('Success').dialog(); 
    } 
    }); 
+0

嘿,我尝试过,但似乎无对话:( – user1897595

+0

你错过了选择的$盈编辑答案现在尝试 –

+0

OMG右它的工作非常感谢你(:。!。 – user1897595

0

应该还是在你if条件||,您可以使用[val()][1]来获取所选元素的值并检查它是否为空。

,你在你的jQuery选择错过$

if(('#firstName').val()=="" 
---^--- //here missing $ 

试试这个

$('#save').click(function(){ 
    if($('#firstName').val()=='' || $('#lastName').val()=='' || $('#contact').val()=='' || $('#email').val==''){ 
    $('#dialog').attr('title','Error').text('All fields are required').dialog(); 
    }else{ 
    $('#dialog').attr('title','Success').text('Success').dialog(); 
    } 
}); 
+0

是它的工作现在。感谢名单。 – user1897595

+0

哦,等等..我得到了成功的消息,但标题仍然是错误。为什么? – user1897595