Jquery alert not working

Hello all

Basically I am trying to display an alert if a ‘0’ is entered into a form input. This does not seem to be working.

Also I would like to customize this slightly. I only want to display the alert if they enter ‘0’ as the first character of that input.

Here is my example, any help is appreciated

http://jsfiddle.net/YMs4q/28/

The reason your demo wasn’t working was because you have the following line in your code which was calling an undefined variable called $input:

$input.prop('disabled', true);

See the below link for an updated version of your demo which i have cleaned up and got working.

http://jsfiddle.net/YMs4q/29/

Thanks, sorry should have seen that.

Couple of things:

  1. When you enter 0 as the first character the alert pops up but the 0 remains as the first character in both the Phone Number boxes. When the alert is called the 0 should be removed as the first character in both of these boxes.

  2. When you enter 0 as the second/third…etc character the alert still pops up. I would only want the alert to pop up if they enter 0 as the first character. At any other point in the text box they should be allowed to enter 0 without the alert popping up.

  3. **NEW FEATURE - I would actually like to impose another rule on this text box. If they enter any character that is NOT numerical, ie letter, space, ( etc I would like another alert to pop up saying: please only use numbers

Thanks again

I would recommend you try the above two points on your own first as they are pretty straight forward to achieve and involve minimal time, if you get stuck i or someone else can assist you from their but i don’t like handing out code unless an attempt was made to solve the problem.

certainly. i shall give it a go and report back

ok i have managed to only allow numerical values

i have tried to remove the 0 from the textbox by using:


if (e.keyCode == 48) {
        alert("Please do not enter 0 as the first character")
        $('#paxphoneno').val = ("");
    }

this does not work.

also with regards to applying the rule to the first character, i think it can be done using an array… but i don’t think i would be able to get it working anytime soon. if i had more time i would persist but i’m so busy with other things if i would take you or another expert ‘minimal time’ i would appreciate some more help.

thanks

here is the updated version
http://jsfiddle.net/YMs4q/38/

It can be a bad user-interface design to throw error alerts at a user when they’re typing things out. What seems to work better than that is to not allow such invalid characters from being typed, and possibly to display the warning somewhere on the screen until something else it typed, or they go to the next field.

Something like the following update should do, where keypress is used to check if anything other than a numeric value is used.

When dealing with the leading 0, it’s not enough to check if the field was empty when 0 was entered, because then it’s possible for someone to type in a number and then go back to the start and add a 0.
So instead, you can use the keyup event which allows you to access the value after the pressed key has been added, so that you can check to see if the start of the value is a 0. If it is, it can be lopped off with a suitable message appearing.

I’ve also added the message as a span with a class of error, along with a bit of CSS to space it out a bit from the field, and as a last touch there’s also a blur event that stops the error from being displayed once they leave the field.

See what you think about the latest update to it, at http://jsfiddle.net/YMs4q/71/

hi paul appreciate the response.

firstly when you press and hold the 0 key, it allows you to enter 000000 without warning and without removal.

i don’t suppose anybody would actually do that but you know, just in case :wink:

also can you actually clarify what conditions the warning displays under. i would prefer if the messages appears immediately.

ie.
as and whenever they enter an illegal character it displays ‘Please only use numbers’
as and whenever they enter a leading 0 it displays ‘Please do not enter 0 as the first character’

Lastly… i have tried to use the code on my webpage and am having difficulties. i have uploaded the entire library to my webspace. jquery functions work on other pages but on this particular page they do not seem to be working…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="http://www.londonheathrowcars.com/scripts/jquery-1.7.1.js"></script>


<script type="text/javascript">

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

$('input, select', '#bookingform').bind('change keyup blur focus', function() {
    $('#paxfullnumber').val(
    $('#paxphonecode').val() + $('#paxphoneno').val().ucfirst());
});

$('#paxphoneno').keypress(function(e) {
    $(this).next('.error').remove();
    if (e.which < 48 || e.which > 57) {
        $(this).after('<span class="error">Please only use numbers</span>');
        return false;
    }
}).keyup(function(e) {
    if (this.value.substr(0, 1) === "0") {
        $(this).after('<span class="error">Please do not enter 0 as the first character</span>');
        this.value = this.value.substr(1);
        $(this).trigger('change');
    }
}).blur(function() {
    $(this).next('.error').remove();
});

</script>

</head>

<body>

<form name="bookingform" id="bookingform">
<p>Your phone number (main):</p>
<p><select name="paxphonecode" id="paxphonecode">
<option value="">...</option><option value="0044">United Kingdom (+44)</option>
</select><input type="text" name="paxphoneno" id="paxphoneno" /></p>

<p>Full number: <input type="text" name="paxfullnumber" id="paxfullnumber" /></p>
</form>
</body>
</html>

do you know why?

http://www.londonheathrowcars.com/bookings/testing1.asp

It is only in the keyup phase that the field value is accessible. With keybown and peypress, it’s the value before the key was pressed that is there instead.
One of those zeros got removed before, but an update can fix that.
To show an error about that before the key is released from keydown means working out if the 0 will end up at the start of the value. From keydown you cannot edit the value, because that value is what there was “before” the key was pressed, so it would mean dealing with some not very compatible insertion bar information to find out if the insertion bar is at the start of the value, which tends to get very messy.

An update now has all leading zeros being removed, so even if you do hold down the zero key, they’re all removed once you let go of that key, by using the following:


this.value = this.value.replace(/^(0+)/, '');

The keypress message about an illegal character appears immediately, and the character is not allowed to be entered.
The keyup message about the leading zero appears the instant that the key is released, and all leading zeros are removed.

You can see it in action at http://jsfiddle.net/YMs4q/74/

Could it be that you need to place the jQuery code in the jQuery wrapper?


jQuery(function ($) {
    // jquery code here
});

paul that is brilliant. i was not nesting the function properly!

also the new fix with the zeros is very good. if you weren’t half the width of the earth away from me i’d give you a big hug!

so there it is, for anybody in england taking international phone numbers, you have the perfect form in jquery

it places the international dialing code before the telephone number and ensures the leading 0 is not registered

http://jsfiddle.net/YMs4q/74/

thanks paul

well it’s not absolutely full proof.

i mean we could impose a character limit based on the international dialing code they select to ensure they always enter a valid phone number.

also if one of our american friends enters their dialing code ‘001’ and then proceeds to enter their phone number including the ‘1’ part of the dialing code it will give a false number such as 00111231231234 (a digit too long)… but to resolve these two issues would involve a lot of research on every conceivable phone number and frankly i do not have the time for that

Hi, just want this field to ALLOW the Tab key (as well as only allow numerical keys).


$('#paxphoneno,#paxphoneno2,#bkphoneno,#bkpaxphoneno,#bkpaxphoneno2').keypress(function (e) {
    $(this).next('.error').remove();
    if (e.which < 48 || e.which > 57) {
        $(this).after('<span class="error">Please only use numbers</span>');
        return false;
    }

I think the Tab is keycode 9 but not sure how to write the statement out.

*Update - I would also like to add delete/backspace and enter keys.

I found this function but am having difficulty incorporating it into my function

example


$(document).ready(function() {
    $("#txtboxToFilter").keydown(function(event) {
        // Allow: backspace, delete, tab and escape
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    });
});

my function


$('#paxphoneno,#paxphoneno2,#bkphoneno,#bkpaxphoneno,#bkpaxphoneno2').keypress(function (e) {
    $(this).next('.error').remove();
    if (e.which < 48 || e.which > 57) {
        $(this).after('<span class="error">Please only use numbers</span>');
        return false;
    }
}).keyup(function(e) {
    if (this.value.substr(0, 1) === "0") {
        $(this).after('<span class="error">Please do not enter 0 as the first character</span>');
        this.value = this.value.replace(/^(0+)/, '');
        $(this).trigger('change'); 
    }
}).blur(function () {
    $(this).next('.error').remove();
});

You can use it as a function called isEditingKey:


function isEditingKey(evt) {
    // Allow: backspace, delete, tab and escape
    if (evt.keyCode == 46 || evt.keyCode == 8 || evt.keyCode == 9 || evt.keyCode == 27 || 
         // Allow: Ctrl+A
        (evt.ctrlKey === true && evt.keyCode == 65) || 
         // Allow: home, end, left, right
        (evt.keyCode >= 35 && evt.keyCode <= 39)) {
             // let it happen, don't do anything
             return true;
    }
    return false;
}

And then use it from within your keypress event, so that it will ignore those non-char characters:


$('#paxphoneno,#paxphoneno2,#bkphoneno,#bkpaxphoneno,#bkpaxphoneno2').keypress(function (e) {
    if (isEditingKey(e)) {
        return;
    }
    $(this).next('.error').remove();
    ...

yes it worked first time thanks