我正在尝试编写一个jquery(ajax)代码,在提交之前检查html表单中的某些字段以进行验证,如果发生任何错误,则消息必须显示在带有id响应的div中,但它不起作用。
$(document).ready(function() {
$('form #response').hide(); //hide the response div in the html
$('#create').click(function(e) {
e.preventDefault(); //stop the form from submitting
var valid = '';
var required = ' is required';
var name = $('form #fname').val();
var email = $('form #email').val();
var username $('form #username').val();
var pword = $('form #password').val();
if (name == '' || name.length <= 2) {
valid = '<p>Your name ' + required + '</p>';
}
if (!email.match(/^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email ' + required
}
if (username == '' || username.length <= 2) {
valid += '<p>A username ' + required + '</p>';
}
if (pword == '') {
valid += '<p>A username ' + required + '</p>';
}
if (valid != '') {
$('form #response').removeClass().addClass('error')
.html('<strong>Please correct the errors below.</strong>' + valid).fadeIn('fast');
}
}); //click function
}); //ready function
&#13;
#response {
border: 1px solid #FF0000;
color: #333;
height: auto;
min-height: 45px;
width: 100%;
margin-bottom: 20px;
}
#response p {
margin: 0;
padding: 0;
}
.error {
background: #FF9F9F url(img/alert.png) no-repeat 5px 10px;
}
&#13;
<form id="createForm" name="theForm" method="post" action="createUser.php">
<legend><span class="icon"><img src="/registerUser/img/createIcon.png"></span> Create New User</legend>
<p><span id="requiredfields">* required field.</span>
</p>
<!--<span id="errorMessage"> </span>-->
<div id="response">
<!--This will hold the message and the response from the server-->
</div>
<input id="fname" type="text" name="fname" placeholder="Name *" pattern="^[A-Za-z ]+$">
<br>
<br>
<input id="email" type="email" name="email" placeholder="Email *" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">
<br>
<br>
<input id="username" type="text" name="username" placeholder="Username *">
<br>
<br>
<input id="password" type="password" name="password" placeholder="Password *">
<br>
<br>
<label for="roles">Roles:</label>
<select id="role" name="roles">
<option>Select Role</option>
<option value="empty"></option>
<option value="Reporter">Reporter</option>
<option value="Lover">Lover</option>
<option value="Other">Other</option>
</select>
<br>
<br>
<input id="create" type="submit" name="createUser" value="Create User">
</form>
&#13;
答案 0 :(得分:1)
在JavaScript和许多其他语言中,=
是一个赋值运算符。这意味着
if(a = 3) { // blah blah blah
不会将a
与3进行比较。相反,它会将值3分配给a
,这可能是您的代码无效的原因。相等的比较运算符是==
,但最好使用===
,因为它在弱比较方面的表现更为一致。如果替换if
子句中的代码,则代码应该有效。