我对表单
有以下语义结构<form class="form-horizontal" name="signUp" id="signUp" novalidate>
<fieldset>
<legend>Sign Up</legend>
<div class="form-group inputEmail">
<label for="inputUsername" class="col-lg-2 control-label" >Username</label>
<div class="col-lg-10">
<input type='email' class="form-control" id="inputEmail" placeholder="Your Email" maxlength="56" />
</div>
</div>
<div class="form-group inputPassword">
<label for="inputPassword" class="col-lg-2 control-label" >Password</label>
<div class="col-lg-10">
<input type='password' class="form-control" id="inputPassword" placeholder="Your Password" minlength="6" />
</div>
</div>
</fieldset>
</form>
我的目标是在keydown上对表单中的特定输入元素执行验证。我有以下jQuery代码片段来完成
$('#signUp').keydown(function(){
signUp.usernameValid(); //performs validation
signUp.passwordValidity(); //performs validation
});
我正在尝试遵循事件委托技术。但是,我遇到并且目前试图弄清楚的问题是,当在表单元素上触发keydown事件时,如何关注特定元素?
根据上面的代码,一旦keydown事件被触发,将为输入元素而不是特定的
触发所有验证。答案 0 :(得分:1)
$('#inputEmail').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
//e.preventDefault();
$("#errg").html("Allow only alphabets").show().fadeOut("slow");
return false;
} else {
var key = e.keyCode;
if (!((key == 8) ||(key == 9) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
$("#errg").html("Allow only alphabets").show().fadeOut("slow");
return false;
}
}
});
答案 1 :(得分:0)
$('#signUp input').on('keydown', function(){
//this will give you the specific element
console.log($(this));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" name="signUp" id="signUp" novalidate>
<fieldset>
<legend>Sign Up</legend>
<div class="form-group inputEmail">
<label for="inputUsername" class="col-lg-2 control-label" >Username</label>
<div class="col-lg-10">
<input type='email' class="form-control" id="inputEmail" placeholder="Your Email" maxlength="56" />
</div>
</div>
<div class="form-group inputPassword">
<label for="inputPassword" class="col-lg-2 control-label" >Password</label>
<div class="col-lg-10">
<input type='password' class="form-control" id="inputPassword" placeholder="Your Password" minlength="6" />
</div>
</div>
</fieldset>
</form>
&#13;