Limit number on an input - 2nd doubt

Asked

Viewed 93 times

4

My goal in a previous post was to put a maximum and minimum value in a text field, a user solved it almost perfectly. Let’s use as an example at most the number 37:

function checa(e){
   const mi = +e.min;
   const ma = +e.max;
   const va = e.value;
   if(va < mi){
      e.value = mi;
   }else if(va > ma){
      e.value = ma;
   }
}
<input oninput="checa(this)" value="1" type="number" min="1" max="37">

However, if the maximum number is for example 10, it will not be able to delete the number 1 to be able to type for example a 7. But the minimum number has to be 1, someone would know how to extend this solution?

Follow the link from the old post: Limit number on an input

  • How ... I didn’t understand?

1 answer

2


In the maximum number scenario be 10, you can change the function checa to allow the field to remain empty, thus allowing the minimum value to be deleted and the value 7 to be inserted:

function checa(e){
   const mi = +e.min;
   const ma = +e.max;
   const va = e.value;

   if(va.length) {
      if(va < mi){
         e.value = mi;
      }else if(va > ma){
         e.value = ma;
      }
   }
}
<input oninput="checa(this)" value="1" type="number" min="1" max="10">


But this can create a problem for you, if this field is mandatory!

If the field is mandatory and is within a form, you can use the attribute required in his input:

<form>
  <input type="number" min="1" max="10" required>
  <input type="submit">
</form>

See that if you leave the field empty, the Submit does not allow sending.


If your field is not within a form and you need it to have a value, you can implement the event onblur so that when you leave the field, if it is empty, a value is inserted, which may be the minimum value:

function checa(e){
    const mi = +e.min;
    const ma = +e.max;
    const va = e.value;

    if (va.length) {
        if(va < mi){
            e.value = mi;
        }else if(va > ma){
            e.value = ma;
        }
    }
}

function valorMinimo(e) {
    if (!e.value.length) {
        e.value = e.min;
    }
}
<input oninput="checa(this)" onblur="valorMinimo(this)" value="1" type="number" min="1" max="10">

  • 1

    If your field is not inside a form, it is semantically incorrect, put it inside a form. Nor does it make sense to have a input out of a form

  • It worked here buddy. It’s inside a yes form. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.