0

I have a form in that I need to validate longtitude and latitude fields.

Code below works well with capturing the keypress. However in the focusout part there are two problems that I just can't figure out:

1/ it is supposed to replace the "not allowed" characters in the field with '', that does not happen

2/ the alert is never triggered

Code looks like this:

    var allowedLongLat = "0123456789.-";

    $("#latitude").keypress( function(e) {
        var chr = String.fromCharCode(e.which);
        if (allowedLongLat.indexOf(chr) < 0)
        {
            alert("The character "+chr+" is not allowed in this field!");
            return false;
        }
    });
    $(document).on("focusout","#latitude",function(){
        var str = $("#latitude").val();
        var wrongchars = [];
        var wrongalert = "";
        for (var i = 0, len = str.length; i < len; i++) {
            if (allowedLongLat.indexOf(str[i]) < 0)
            {
                wrongchars.push(str[i]);
            }
        }
        jQuery.each(wrongchars , function(index, value){
             $("#latitude").val( str.replace(\'/\'+value+\'/g\', \'\') );
             wrongalert += value;
        });                 
        if ( wrongalert.lenght > 1 )
        {
            alert("The characters "+wrongalert+" are not allowed in this field!");
        }
    });

Any ideas what I am missing out?

2
  • Just to be sure, we're talking decimal degrees, right? For example: -4.32135123, 15.5123123, yes? Commented Nov 23, 2014 at 3:27
  • yes, for google maps coords Commented Nov 23, 2014 at 3:28

1 Answer 1

1

Found some errors in code

$("#latitude").val( str.replace(\'/\'+value+\'/g\', \'\') );

has some typo mistake,

if ( wrongalert.lenght > 1 )

typo error, it should be length.

I made this jsfiddle.

var allowedLongLat = "0123456789.-";

$(document).on("focusout","#latitude",function(){
    var str = $("#latitude").val();
    var wrongchars = [];
    var wrongalert = "";
    for (var i = 0, len = str.length; i < len; i++) {
        if (allowedLongLat.indexOf(str[i]) < 0)
        {
            wrongchars.push(str[i]);
        }
    }
    //console.log(wrongchars);
    jQuery.each(wrongchars , function(index, value){
        console.log(value);
         $("#latitude").val( $("#latitude").val().replace(value, '') ); // I simplified here
         wrongalert += value;
    });     
    if ( wrongalert.length > 1 )// here was typo error
    {
        alert("The characters "+wrongalert+" are not allowed in this field!");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.