blsn
blsn

Reputation: 1093

Enable field when selecting from drop-down box

My contact form page, for user edit details, has two drop-down fields, ‘country’ and ‘city’. I would like when a user is edit his details that the ‘city’ field will be disabled until something is selected in the ‘country’ drop-down menu.

<form name="item" action="<?php echo base_url(true) ?>" method="post">

<label><?php _e('Country', 'my_theme'); ?></label>
<?php ItemForm::country_select(get_countries(),user()) ; ?>

<label><?php _e('City', 'my_theme'); ?></label>
<?php ItemForm::cities_select(get_cities(),user()) ; ?>

<button class="itemFormButton" type="submit"></button>
</form>

I’ve tried ‘onchange’ in javascript, probably with wrong syntax…

How can I create this? Thx.

Upvotes: 1

Views: 2099

Answers (2)

SubRed
SubRed

Reputation: 3187

This might help you http://jsfiddle.net/GZ269/. This uses jquery.

Country:<br />
<select id="drop1">
    <option value="">Select Country</option>
    <option value="c1">Country 1</option>
    <option value="c2">Country 2</option>
</select>
<br />
City:<br />
<select id="drop2" disabled >
    <option value="">Select Country</option>
    <option value="c1">Country 1</option>
    <option value="c2">Country 2</option>
</select>

Javascript function:

$("#drop1").change(function(){
    var country = $(this).val();

    if(!country){
        $("#drop2").attr("disabled", true);
        return false;
    }

    $("#drop2").attr("disabled", false);
});​

Upvotes: 1

Nicol&#225;s Ozimica
Nicol&#225;s Ozimica

Reputation: 9738

You should do this with Javascript's onchange event, and when this event is fired, you have two options:

  • Query the cities for the country selected with ajax.
    • This is good if you support (almost) all the countries in the world.
    • Here you must develop a PHP script to be queried when this event is fired.
  • Have a great array with the cities for all the countries supported.
    • Too bulky if need you to cover many countries.
    • Less flexible, if you need to add more cities for any country.

Upvotes: 0

Related Questions