I’ve got a plugin I’m working on, part of which consists of a ‘conditional’ dropdown on the options page. Basically, I’ve got a dropdown with three options, and a second dropdown gets populated with info from the database depending on what is selected in the first dropdown. Problem is, I’m at a loss as to how to populate the second dropdown! I’m not really that great with AJAX, but it seems the likely solution. Any thoughts from the more seasoned devs out here?
EDIT: Here’s where I currently am, but it never seems to get run:
<form action="<?php echo site_url() ?>/wp-admin/admin.php?page=ad_manager&pagetype=addedit&pid=<?php echo $_REQUEST['id']; ?>" method="post" name="ad_success">
<table cellpadding="5" class="widefat post fixed">
<thead>
<tr>
<th><strong><?php if($_REQUEST['id'] != '') { _e('Edit Ad'); } else { _e('Create Ad'); } ?></strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label for="gtad_condition">
<strong><?php _e('Ad Condition'); ?>:</strong>
<select name="ad_condition" id="ad_condition">
<option value="">Select an option...</option>
<option value="is_city">Is City</option>
<option value="is_location">Is Location</option>
<option value="is_page">Is Page</option>
</select>
</label>
<label for="gtad_location">
<select name="ad_location" id="ad_location"></select>
</label>
</td>
</tr>
</tbody>
</table>
</form>
<script>
jQuery(document).ready(function() {
$ad_condition = $("select[name='ad_condition']");
$ad_location = $("select[name='ad_location']");
$ad_condition.change(function() {
if ($(this).val() == "Is City") {
$("select[name='ad_location'] option").remove();
$("<option>Test</option>").appendTo($ad_location);
}
});
});
</script>
The reason why your code above does not work, is because
$("mySelect").val()
returns thevalue
attribute of the<option>
, not the text between the beginning and end tag. See my fiddle: http://jsfiddle.net/XhujD/ .So, you solve the problem by changing
into
Using AJAX to populate the second dropdown when the first one has changed will basically look as follows: