Jump to content

[SOLVED] populate dropdown w/o submit


tet3828

Recommended Posts

So Ive got some arrays; one array is most of the U.S states. the other arrays are names of clinics my company has within the selected state. I want to be able to select a state from a drop down and have another drop down next to it that will populate itself automatically.... without having to press a submit button.

 

 

any suggestions or links to examples? thanks!

Link to comment
https://forums.phpfreaks.com/topic/54823-solved-populate-dropdown-wo-submit/
Share on other sites

Well, you definitely need javascript, but you may be able to implemetn it all with Javascript or - if the lists are very large- you may need to use AJAX in order to grab the data fro the lists. Which you use would be dependent upon the number of states and number of clinics in each state.

 

Here is a javascript only implementation:

 

<html>
<head>

<script type="text/javascript">


// State lists
var states = new Array();
states['Canada'] = new Array('Alberta','British Columbia','Ontario');
states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco');
states['United States'] = new Array('California','Florida','New York');


function setStates(){

  cntrySel = document.getElementById('country');
  cntryVal = cntrySel[cntrySel.selectedIndex].value;

  stateList = (states[cntryVal]) ? states[cntryVal] : false ;

  changeSelect('state', stateList);

}

function changeSelect(fieldID, newList) {

  selectField = document.getElementById(fieldID);
  selectField.options.length = 0;

  if (newList!=false) {

    for (i=0; i<newList.length; i++) {
      selectField.options[selectField.length] = new Option(newList[i], newList[i]);
    }
    selectField.disabled = false;

  } else {

    selectField.options[selectField.length] = new Option('None Available', '');
    selectField.disabled = true;

  }
}

</script>

</head>

<body onload="setStates();">
<form name="test" method="POST" action="processingpage.php">

Country: 
<select name="country" id="country" onchange="setStates();">
  <option value="Canada">Canada</option>
  <option value="Mexico">Mexico</option>
  <option value="United States">United States</option>
</select>
<br>

State: 
<select name="state" id="state">
  <option value="">Not Applicable</option>
</select>
<br>

</form>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.