View Single Post
  #16 (permalink)  
Old May 15th, 2004, 03:31 AM
Imar's Avatar
Imar Imar is offline
Wrox Author
Points: 72,073, Level: 100
Points: 72,073, Level: 100 Points: 72,073, Level: 100 Points: 72,073, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

I think some explanation about a few basic principles is in order here.

Consider this:

<script>
  var myClientSide = '<%=myServerSide%>';
</script>

In this code, the <%= %> is a short cut for Response.Write(myServerSide) at the server. So what happens is that a server side variable is written to the client side.
Omitting the = would result in just a variable name listed in the code, but no output.

In your select function, the value of SomeASPVariable I proposed shouldn't be the name of the form element, but the actual value you want to preselect. So, if you have a drop-down with first names, SomeASPVariable could contain John for example, again at the server, to preselect the item wih the value John.

Then this code:

 PreselectMyItem('<%=SomeASPVariable%>');

would end up like this:

 PreselectMyItem('John');

Then the code Snib and I gave you earlier is run. The JavaScript code loops through all the elements in your drop down, looking at its value property, and determines whether it should be selected or not:

I modified the code a bit so it works now, and should run in all browsers:
Code:
<html>
<head>

<script type="text/javascript">
  function PreselectMyItem(itemToSelect)
  {
    // at this point, itemToSelect holds 'John'

    // Get a reference to the drop-down list
    var myDropdownList = document.frmTest.lstNames;

    // Loop through all the items
    for (i = 0; i < myDropdownList.options.length; i++)
    {
      if (myDropdownList.options[i].value == itemToSelect)
      {
        myDropdownList.options[i].selected = true;
        break;
      }
    }
  }
</script>
</head>

<body onload="PreselectMyItem('John');">

<form id="frmTest" name="frmTest">
  <select id="lstNames" name="lstNames">
    <option value="Snib">Snib</option>
    <option value="Imar">Imar</option>
    <option value="John">John</option>
  </select>
</form>
</body>
</html>
The only change to this code you must make is the value you pass to the function. Instead of:

  <body onload="PreselectMyItem('John');">

you should do something like this:

  <body onload="PreselectMyItem('<%=SomeASPVariable%>');">

Instead of passing the item in the onload event, you could also write it out as a variable somewhere in your JavaScript code block.

Does this clarify things??

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
While typing this post, I was listening to: Kill You by KoRn (Track 14 from the album: Life Is Peachy) What's This?
Reply With Quote