jQuery form zip code to state function

Posted by Dakota R. on Stack Overflow See other posts from Stack Overflow or by Dakota R.
Published on 2009-11-25T18:13:16Z Indexed on 2010/06/05 19:02 UTC
Read the original article Hit count: 199

Filed under:
|
|
|

I'm trying to convert a preexisting javascript function into a jQuery function. The function comes from http://javascript.internet.com/forms/zip-to-state.html and aims to convert a user-entered zip code into a state. I'm using jQuery 1.3.2, with all the necessary plugins, but I'm not very familiar with jQuery syntax and how to convert this from plain ol' Javascript syntax.

The setState function takes two parameters, the zip code element and the state element, so I'm trying to do something like this:

$('$zip_code').change( function () { setState($(this), $('#state')); });

Any thoughts on this syntax? Thanks, Dakota

function getState(zip) {
    if ((parseInt(zipString.substr(zip / 4, 1), 16) & Math.pow(2, zip % 4)) && (zip.length == 5))
    	for (var i = 0; i < stateRange.length; i += 7)
    		if (zip <= 1 * stateRange.substr(i, 5))
    			return stateRange.substr(i + 5, 2);
    return null;
}

function setState(txtZip, optionBox) {
    if (txtZip.value.length != 5 || isNaN(txtZip.value / 4)) {
    	optionBox.options[0].selected = true;
    	alert("Please enter a 5 digit, numeric zip code.");
    	return;
    }

    var state = getState(txtZip.value);

    for (var i = 0; i < optionBox.options.length; i++)
    	if (optionBox.options[i].value == state)
    		return optionBox.options[i].selected = true;
    for (var i = 0; i < optionBox.options.length; i++)
    	if (optionBox.options[i].value == "XX")
    		return optionBox.options[i].selected = true;
}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery