Frage

 <input type="text" name="user" maxlength="10">

I have some code:

$("#user").keyup(function(e){ 
  if($("#user").val().length < 4) {$("#spanUser").html("Too Short !");}  //works

How can I write:

if($("#user").val().length > 0 < 4)... // between 1 and  4
if($("#user").val().length == 10) {play a beep sound;}
War es hilfreich?

Lösung

Firstly, you should use the keypress event, as your current code allows someone to hold down the key and get multiple characters.

$("#user").keypress(function(e) { 
    var userVal = $("#user").val();
    if (userVal.length >= 1 && userVal.length <= 4) {
        $("#spanUser").html("Too Short !");
    }
    else if (userVal.length == 10) {
        // play beep sound
    }
});

Andere Tipps

use && operator..

try this

var valLength=$("#user").val().length ;  //declare a variable..  which is bit faster than calling a selector again n again

if(valLength > 0  && valLength< 4){  //use && operator here
   //do your stuff
}else if(valLength == 10){  //else if length is 10..
   //play beep sound
}
if($("#user").val().length > 0  && $("#user").val().length< 4)
{
    //between 1 and  4
}

Do you mean something like:

var length = $("#user").val().length;
if(length > 0 && length < 4)
{... // between 1 and  4
}
else if(length == 10)
{play a beep sound;}

you can apply this kind of regular expression for this

^[A-Za-z]{1,4}$

You can use range quantifier {min,max} to specify minimum of 1 char and maximum of 4 char

var patt1=new RegExp("^[A-Za-z]{1,4}$");
if(patt1.test($("#user").val())
{
}

I think a check with one condition would suffice. Seeing as how you have a textbox, the length can only be a positive number anyway.

if($("#user").val().length) < 4) {
    //your code.
}
$("#user").keyup(function(e){ 
    var elem = $("#user");
  if(elem.val().length < 4) {
      $("#spanUser").html("Too Short !"); //works
   } else if(elem.val().length > 0 && elem.val().length < 4) {
      //Your code here    
    } else if(elem.val().length == 10) {
      //play beep sound    
    } 

From a user experience perspective there are some issues about your implementation here.

First, as an end user I would not like to see a warning as soon as I start to write on a text box. You better show this alert/warning when the user is done with the user textbox. You should consider lost focus event for this.

Second it's not a good idea to play a sound when an input has reached it's maximum. The device that your user is using may not have sound functionality or a disabled sound device. Even the user could be hearing imparient. MaxLenght should be enough for most cases. If you want more emphasis on this restriction you can place a warning next to input, with somehow low visibility.

I know this is not an answer to your question but can help you in some way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top