View Full Version : Easy request

01-09-2003, 07:30 PM
Man, I haven't written any js in so long I've gotten rusty. This has gotta be easy, maybe someone will help with an example.

I've got a form. It has three text input fields I'm interested in here: country, state, city.

If the country is USA, I want city to be a required field. If it's not the US or USA, then it's not required. Any help?

01-09-2003, 07:47 PM
if (document.FormName.Country.value=="USA") {
require state

01-10-2003, 01:15 AM
I'm assuming you're using a country dropdown and a state dropdown - OOPS! I see you're using a text field for BOTH, VERY bad idea!

You really need to use a <select> dropdown for both of them, because you can't depend (or validate) on what users might type in... like:

Untied Status


or whatever... (and believe me, I've seen worse than that!) ;)

Then, as suggested above, use something like:

var f = document.FormName;
if(f.Country.options[f.Country.selectedIndex].value=="USA" && f.State.options[f.State.selectedIndex].value=="") {
alert('Yo buddy! You forgot to enter the State you live in!');
return false;

Just another reason to use a dropdown - consider you might use state abbreviations to validate against (and/or save to a database). If someone were to instead enter:


in a text field, and you only looked at the first two characters, your script would assume they entered "NE", which is actually Nebraska.

I suggest using State/Country dropdowns because those are at least finite values which can easily be obtained. If you need a pretty up-to-date listing of states and/or countries and their respective values to use in a dropdown, let me know. :D

01-10-2003, 10:28 PM
yup. They are text fields. I didn't design it, just inherited it.

I think I will convert them to drop-list boxes. Thanks for the suggestion.