tags:

views:

42

answers:

2

Hello. I am creating a site that requires a very small postcode checker. I have approx 8 postcode prefix's, HX, HD, BD, LS etc in an array. I also have a simple input field and submit btn. When the user types in a postcode for example HX5 9DU I want Jquery to check the array, if there is match for the first 2/3 letters I want a div to fade in displaying a message.

How would I do this? Many thanks in advance.

+1  A: 

Here's one way to do it:

http://jsfiddle.net/uNKhs/3/

HTML:

<div id="message">some message</div>

<input type="text" id="myInput" />​

jQuery:

$(function() {  // Wrap the code such that it will run after document loads

    $("#message").hide();   // First hide the message

    var prefix = ['HX', 'HD', 'BD', 'LS'];   // Create your array of prefixes

    $('#myInput').keyup(function(e) {   // Trigger an event handler on each 'keyup'

        var value = $(this).val();   // Grab the current value of the input

            // Store first two characters in a variable, and convert to upper case
        var firstTwo = value.substr(0,2).toUpperCase();


             // Check that the length of the input is greater than one,
             //    and that the firstTwo characters are in the prefix array
        if(value.length > 1 && ($.inArray(firstTwo, prefix) >= 0)) {

                // If so, find the hidden element with ID "message" and fade it in.
            $("#message:hidden").fadeIn();
        }
    });

});

Some related jQuery docs:

.hide() http://api.jquery.com/hide/

$.inArray() http://api.jquery.com/jQuery.inArray/

.fadeIn() http://api.jquery.com/fadein/

.keyup() http://api.jquery.com/keyup/

.val() http://api.jquery.com/val/


EDIT:

When running jQuery code, it is usually best to have your code run after the document has loaded. You can do this a couple different ways.

$(document).ready(function() {
    // My jQuery code
});

or

$(function() {
    // My jQuery code
});

The two will accomplish the same thing.

I updated my answer to include the second version.


BONUS:

This version will update the input with the upper case version if the user types lower case characters for the first two characters.

EDIT: Also, it shows a fail message if a match in the array is not found.

http://jsfiddle.net/uNKhs/8/

$(function() {
    $("#message").hide();
    $("#fail").hide();

    var prefix = ['HX', 'HD', 'BD', 'LS']

    $('#myInput').keyup(function(e) {
        var value = $(this).val();
        var firstTwo = value.substr(0,2);
        var firstTwoUpper = firstTwo.toUpperCase();

        if(firstTwo != firstTwoUpper) {
            $(this).val( value.replace(/^\w\w/, firstTwoUpper) );
        }
        if(value.length > 1) {
            if($.inArray(firstTwoUpper, prefix) >= 0) {
                $("#fail").hide();
                $("#message:hidden").fadeIn();
            } else {
                $("#message").hide();
                $("#fail:hidden").fadeIn();
            }
        } else {
            $("#message").hide();
            $("#fail").hide();
        }
    });
});
​
patrick dw
Wow this is great thanks Patrick I do appreciate the help
mtwallet
Glad it helped! :)
patrick dw
Patrick am I missing something? I cannot get it to work in your example or on local machine. Thanks.
mtwallet
A couple basic questions - Do you have the jQuery library loaded before your code runs? And is the code set up to run after the document loads? I'll update my answer for the second question, but let me know about the first.
patrick dw
Sorry Patrick just realised it is case sensitive! If a user adds a wrong postcode how would I handle that?
mtwallet
Not a problem. I updated my answer to convert the value stored in `firstTwo` to upper case. `var firstTwo = value.substr(0,2).toUpperCase();` Should take care of you. I updated the jsFiddle link too.
patrick dw
Threw a bonus in there for you. I added a version that will convert the first two characters to uppercase if one (or both) of them was typed as lower case.
patrick dw
That is awesome Patrick! Thanks a lot for all your help. I was just trying to add an else statement to fade in a #fail div if the user enters a postcode that does not match any in the array no luck yet but will keep trying.
mtwallet
Here's a hint. Take this `$.inArray(firstTwoUpper, prefix) >= 0` out of the `if()` condition, and use it for the condition in another `if()` statement that is nested inside the original. Then the else will only run if `value.length` is greater than 1.
patrick dw
Patrick I have tried a few ways now failed on all fronts. I have edited my initial request to include my code for the else statement am I on the right lines? I have tried without the (value != prefix)
mtwallet
You were close. You just needed to place the `else` statement inside the original `if` (after the new `if`). Also, the new `fadeIn()` had a lowercase `i`, as in `fadein()`, which would not work. I updated my answer (at the bottom), and updated the jsFiddle link. If you don't mind, I'm going to roll back your question to the original version in order to maintain its integrity for future readers.
patrick dw
Patrick I did try this solution first my mistake was the capitalisation on the "i" when it didn't work I moved on trying other things. I have learned some valuable things today, thank you for your help.
mtwallet
One final we could add above if(value.length > 1) is if(value.length < 1) {$("#message").hide(); $("#fail").hide();} so if a user tries multiple times it will hide the responses again.
mtwallet
I would probably add the `hide()` calls above each `fadeIn()`. That way if (for example) the `#message` element is shown, it won't be hidden and faded in again with each keystroke. I updated my answer, and the jsFiddle link.
patrick dw
Oh, you want to hide both messages if the keystroke is 1 or less? If so, just add an `else` to that first `if` statement. I'll update for that as well.
patrick dw
A: 

I guess it would be best if you involve some serverside actors to this episode.

Doing something like:

$.getJSON('/CheckPrefix', { query = $('#prefixInpunt').val() }, function(responseMsg) {
    $('#messageDiv').show().html(responseMsg);
})

You can store all your codes in a db, then just query the db with the param you get in the json call and craft the message on your server and send it to the UI.

JoseMarmolejos