New Bie
New Bie

Reputation: 105

How to Show Alert When Text Field Length Greater than Defined Number

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>

Upvotes: 1

Views: 4235

Answers (4)

New Bie
New Bie

Reputation: 105

<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>

Upvotes: 0

Darshit Patel
Darshit Patel

Reputation: 730

<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>

Upvotes: 3

Nichsici Dejan
Nichsici Dejan

Reputation: 104

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");
}

Upvotes: 5

ded
ded

Reputation: 150

Should be:

if ((x.value.length > 35) || (y.value.length > 35))

Upvotes: 1

Related Questions