Skip to content Skip to sidebar Skip to footer

How To Find All Instances And Display In Alert

I have a textbox which users will type or paste comma separated values such as A123456,B123456,C123456,D123456 These entries need to meet certain criteria, one of which is that the

Solution 1:

What about using filter, like this:

varval = document.getElementById("Textbox1").value,
    err = $(val.split(',')).filter(function(){ returnthis.length != 7; }).toArray();
if (err.length) {
    alert("All entries must be seven (7) characters in length.  Please correct the following entries: \n" + err);
    returnfalse; 
}
returntrue; 

Demonstration

Or grep, like this:

varval = document.getElementById("Textbox1").value,
    err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
    alert("All entries must be seven (7) characters in length.  Please correct the following entries: \n" + err);
    returnfalse; 
}
returntrue; 

Demonstration

Solution 2:

On can do this : -On change event, you check every values but the last one (which is not finished yet). If a comma is typed and the last one is not correct, do not allow the user to keep typing and remove the comma (or it will be endless loop).

You have solved the looking-for-the-error problem.

You can also search for some kind of setCursorPosition ..

Solution 3:

Don't use alert(). Make a <div> like this and append all messages to it, this way the use gets all messages at once. And it's a nicer way to display errors also.

HTML:

<div id="alerts"></div>

JS:

var errors=""; //put HTML for error messages here
$("#alerts").append(errors);

Solution 4:

You can do it easily, by storing all bad entries into a variable and then getting all alert a message with all entries.

Like this one:

val = document.getElementById("Textbox1").value;
val = val.split(',');
    var is_Error = false;
    var ErrrMsg = "All entries must be seven (7) characters in lenght.  Please correct the following entries:\n";
    for(var i=0;i<val.length;i++){    
       if((val[i].length !=7) && (val[i].length !=0)){
          ErrrMsg += val[i] +  ",";
          is_Error = true;
       }    
    }
    if(is_Error == true){
      alert(ErrrMsg.substring(0,(ErrrMsg.length - 1)));/*Here "substring" is used to remove last comma into message string.*/returnfalse;
    }
    returntrue;

Try in fiddle

Post a Comment for "How To Find All Instances And Display In Alert"