I have a PHP array that populates the first select dropdown list so the user can select a occupation. After the occupation is selected, the second drop down list gets loaded with the job positions for that occupation using a JavaScript function.
Then I use jQuery to change the action attr of the form based on the value of the second drop down. But it returns null because the <option></option>
are being loaded through the JavaScript. If I hard code the <option></option>
in the select box, then it works.
Just as a note. I am not using a database. I'm using a php array to hold the data for the 2 drop down lists. The array is already loaded on the page as an include at the top of the php page.
Three part question here.
First - how do I resolve my issue with the action attr?
Second - is there a way to accomplish the populating the second drop down using a different method which may work better?
Third - And if it is ajax, how can it get the php array data without pulling it from the server again, since the array is already loaded into the php page?
Here's my code arrangement
PHP Array
$pages = array(
// Engineer
'Engineer' => array('pageTitle' => 'Engineer', 'subpages' => array(
'Software Engineer' => 'Software',
'Embedded Software Engineer' => 'Embedded Software',)),
// Analyst
'Analyst' => array('pageTitle' => 'Analyst', 'subpages' => array(
'Systems-Analyst' => 'Systems',
'Data-Analyst' => 'Data',))
);
The Select and foreach loop
echo '<form method="POST" action="?position=" id="menuform">
<select name="occupation" id="occupation">
<optgroup label="Select Occupation">
<option value="" selected disabled>Select Occupation</option>';
foreach ($pages as $filename => $value) {
echo '
<option value="'.$filename.'"'.((strpos($position, $filename) !== false) ? ' selected' : '').'>'.$filename.'</option>';
} // foreach pages
echo '
</optgroup>
</select>
<select name="position" id="position" onchange="this.form.submit()">
</select>
</form>
';
JavaScript
<script type="text/javascript">
var occupation = document.getElementById("occupation");
var position = document.getElementById("position");
onchange(); //Change options after page load
occupation.onchange = onchange; // change options when occupation is changed
function onchange() {
<?php foreach ($pages as $filename => $value) {?>
if (occupation.value == '<?php echo $filename; ?>') {
option_html = "\n<? echo'<option selected disabled>Select Position</option>'; ?>\n";
<?php if (isset($value ['subpages'])) { ?>
<?php foreach ($value ['subpages'] as $subfilename => $subpageTitle) { ?>
option_html += "<? echo '<option value=\''.urlencode($subfilename).'\''.(($position == $subfilename) ? ' selected' : '').'>'.$subpageTitle.' '.$filename.'</option>'; ?>\n";
<?php } ?>
<?php } ?>
position.innerHTML = option_html;
}
<?php } ?>
}
</script>
jQuery
$('#menuform').attr('action',$('#menuform').attr('action')+$('#position').val());