Reputation: 7966
<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;}
Upvotes: 0
Views: 1130
Reputation: 5986
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.
Upvotes: 1
Reputation: 4617
$("#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
}
Upvotes: 1
Reputation: 337743
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
}
});
Upvotes: 1
Reputation: 2322
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.
}
Upvotes: 1
Reputation: 176956
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())
{
}
Upvotes: 1
Reputation: 2963
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;}
Upvotes: 1
Reputation: 46900
if($("#user").val().length > 0 && $("#user").val().length< 4)
{
//between 1 and 4
}
Upvotes: 1
Reputation: 36551
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
}
Upvotes: 1