I am a New Bie in Programming, I was creating a code by which how can i limit the user to enter value within defined numbers.
I want the user to enter field value not more than 35 characters or length.
Here is My Written Code but it's is not working
i use onkeyup methodology
function handleChange() { var x = document.getElementById("fname"); var y = document.getElementById("lname"); if ((x.value > 35) || (y.value > 35)) { alert("value should less than 35"); } }
<form onkeyup="handleChange()"> Enter your fname: <input type="text" id="fname"> Enter your lname: <input type="text" id="lname"> </form>
you can either do it from HTML with the maxlength attribute.. so you won't need the handleChange function. the user will simply be limited to a set number of characters. more info here : https://www.w3schools.com/tags/att_input_maxlength.asp
<input type="text" id="fname" maxlength="35">
<input type="text" id="lname" maxlength="35">
or what you were trying to do, but add .length
so..
if ((x.value.length > 35) || (y.value.length > 35))
{
alert("value should less than 35");
}
<form action="/action_page.php">
Username: <input onkeydown="handleChange()" id="fname" type="text" name="usrname" maxlength="36"><br>
Username: <input onkeydown="handleChange()" id="lname" type="text" name="usrname" maxlength="36"><br>
<input type="submit" value="Submit">
</form>
<script>
function handleChange() {
var x = document.getElementById("fname").value;
var y = document.getElementById("lname").value;
console.log(x);
if ((x.length > 35) || (y.length > 35))
{
alert("value should less than 35");
}
}
</script>
应该:
if ((x.value.length > 35) || (y.value.length > 35))
<form onkeyup="handleChange()">
Enter your fname: <input type="text" maxlength="35" id="fname">
Enter your lname: <input type="text" maxlength="35" id="lname">
</form>
<script>
function handleChange() {
var x = document.getElementById("fname");
var y = document.getElementById("lname");
if ((x.value.length > 34) || (y.value.length > 34))
{
alert("value should less than 35");
}
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.