Link to home
Start Free TrialLog in
Avatar of jset_expert
jset_expertFlag for Australia

asked on

Selected list item with javascript

Hi,

this question is a continuation from the following question;

https://www.experts-exchange.com/questions/22961965/Run-Javascript-Function-On-Page-Load.html

How set the selected value from the state drop down with Javascript?

As you can see from the previous question, I build my drop down list with PHP and javascript. When the page is refreshed, then so is the value that the user selected.

ASKER CERTIFIED SOLUTION
Avatar of gops1
gops1
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jset_expert

ASKER

Hi can you relate that code back to my drop list, which is dynamically assigned using PHP and Javascript.

i can see that the '.selectedIndex' function will set the option, but not sure how to associate this back to my existing code.
I am weak in PHP, but tell me one thing what value are you going to pass, is it the number, or the value that you are going to pass.
i will pass a number, this will be the state unique id from the db, which is also the value for the option on the drop list.

thanks
Avatar of Michel Plungjan
I am assuming your have a country drop and a state drop

If the statedrop needs to match the country drop you could do this:

I also assume you have a standard cookie script - if not, I can give you one

You need to do a
setCookie('countrystate',document.frmCheckout.ddlCountry.selectedIndex+'|'+document.frmCheckout.ddlState.selectedIndex);

in your onChange of each select and add this script
<script language="javascript">
function init() {
  var countryIndex = document.frmCheckout.ddlCountry.selectedIndex; 
  if (countryIndex > 0) {
    getStates(document.frmCheckout.ddlCountry.options[document.frmCheckout.ddlCountry.selectedIndex].value);
  }
  var sels = getCookie('countrystate');
  if (sels) {
     var countrystate = sels.split('|');
    if (countryState[0] == countryIndex) { // did we have the same country as previous
      document.frmCheckout.ddlState.selectedIndex=countryState[1]; // set the state to the same state
    }
  }
}
</script>

Open in new window

I am not using cookies at all at the moment.

All the data is stored with variables on the current page.

I can grab the state variable selected, do I need to use cookies?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Forced accept.

Computer101
Community Support Moderator