Using javascript "onchange" for dynamic update

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
keithh0427
Forum Newbie
Posts: 15
Joined: Thu Dec 16, 2004 8:17 am

Using javascript "onchange" for dynamic update

Post by keithh0427 »

I'm trying to use the "onchange" feature of javascript to update dependent fields within the same form. Basically, when a user enters or changes a zipcode, the system will look up the corresponding city and state from a table and then populate or re-populate the corresponding form text fields.

I'm sure this has been done before and I'm trying to not re-invent the wheel on this.
User avatar
Joe
Forum Regular
Posts: 939
Joined: Sun Feb 29, 2004 1:26 pm
Location: UK - Glasgow

Post by Joe »

What software are you using to detect the city, state etc?. Or, are you doing this manually?.
keithh0427
Forum Newbie
Posts: 15
Joined: Thu Dec 16, 2004 8:17 am

Post by keithh0427 »

I'm using PHP and MySQL
User avatar
Joe
Forum Regular
Posts: 939
Joined: Sun Feb 29, 2004 1:26 pm
Location: UK - Glasgow

Post by Joe »

Well you will need to integrate software on your server which allows you to trace 'zip codes' etc. That is unless you decide to type each zip manually which would take forever :O
keithh0427
Forum Newbie
Posts: 15
Joined: Thu Dec 16, 2004 8:17 am

Post by keithh0427 »

Not sure I understand or made my question very clear. I have a database of all zipcodes in the US that I will be using.

If the user types in a zipcode, it should execute a php-based query to lookup the city and state. The city and state would then be populated in the appropriate text fields within the form. If the user retypes the zipcode, then it would execute the query again. and once more populate the appropriate fields.

The zipcodes are unique and would only return one row.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

<?php
if (!empty($_POST['zip']))
{
$sql = "SELECT * FROM `table` WHERE `zip` = '".$_POST['zip']."' LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_assoc($result);
//output your stuff here
echo $row['state']; //assuming state is a column
}
else
{
echo 'no match found';
}
?>
You should also make sure you validate $_POST['zip'] before plugging it directly into the query for security reasons

There is no reason you need to use the onChange function unless you are using a dropdown menu.. if so just make the form submit itself.

Also, this is assuming that the user can only search for 1 criteria at a time...
keithh0427
Forum Newbie
Posts: 15
Joined: Thu Dec 16, 2004 8:17 am

Post by keithh0427 »

thanks.

this works just fine.
Post Reply