以下是我的登录表单,因为我想限制用户在userName字段中输入8个字符,但它不能正常工作以下是我的代码:
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label for="username">Username:</label> <input type="text"
name="username" id="username" value="" maxlength="8" /> <label for="password">Password:</label>
<input type="password" name="password" id="password" value="" /> <label
for="dob">Date of birth:</label> <input type="password"
type="password" name="dob" id="dob" value="" />
</div>
<div >
<fieldset class="ui-grid-a" >
<div class="ui-block-a" >
<input type="submit" data-role="button" value="Login"
id="submitButton">
</div>
<div class="ui-block-b">
<input type="reset" data-role="button" value="Cancel"
id="cancelButton">
</div>
</fieldset>
</div>
</form>
</div>
<script type="text/javascript">
</script>
<script type="text/javascript">
$("#username").live('keydown', function (event)
{
if ((event.keyCode.length>8))
{
event.preventDefault();
}
});
</script>
但是用户仍然可以在UserName字段中输入任意数量的字符。这段代码有什么问题?任何建议将不胜感激。提前致谢
答案 0 :(得分:4)
在输入字段中添加maxlength
,而不是使用脚本进行限制。
<input type="text" name="username" id="username" value="" maxlength="8" />
答案 1 :(得分:4)
你需要什么javascript?只需将maxlength
属性添加到输入字段即可。
<input type="text" name="usrname" maxlength="8" />
这很简单。
答案 2 :(得分:1)
<script type="text/javascript">
function countChars(countfrom,displayto) {
var val = document.getElementById(countfrom).value;
val = val.replace(/[^a-zA-Z0-9]/igm, "");
var len = val.length;
document.getElementById(displayto).innerHTML = len;
onkeydown = function (e) {
if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 9 && e.keyCode != 13 && e.keyCode != 16 && e.keyCode != 17 &&
e.keyCode != 18 && e.keyCode != 19 && e.keyCode != 20 && e.keyCode != 27 && e.keyCode != 33 && e.keyCode != 34 &&
e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40 &&
e.keyCode != 45 && e.keyCode != 91 && e.keyCode != 92 && e.keyCode != 93 && e.keyCode != 112 && e.keyCode != 113 &&
e.keyCode != 114 && e.keyCode != 115 && e.keyCode != 116 && e.keyCode != 117 && e.keyCode != 118 && e.keyCode != 119 &&
e.keyCode != 120 && e.keyCode != 121 && e.keyCode != 122 && e.keyCode != 123 && e.keyCode != 144 && e.keyCode != 145
&& len >= 8)<!-- change the value of len to the number of characters required-->
e.preventDefault();
}
}
</script>
<h1>Day-3 Task-1</h1>
<br /><h2>Counting Number of Characters with Elimination of Special Charecters</h2>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> Characters entered.