Link to home
Start Free TrialLog in
Avatar of narmi2
narmi2

asked on

div tag item select (part 2)

Avatar of amit_g
amit_g
Flag of United States of America image

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

<script>
var Key_Up = 38;
var Key_Down = 40;
var MaxLength = 5;

var g_CurrentIndex = -1;

function OnKeyDownHandler(e)
{
      var key;

      if(window.event)
      {
            key = e.keyCode
      }
      else if(e.which)
      {
            key = e.which
      }

      if (key == Key_Down)
      {
            g_CurrentIndex++;

            if (g_CurrentIndex >= MaxLength)
            {
                  g_CurrentIndex = MaxLength - 1;
            }
      }
      else if (key == Key_Up)
      {
            g_CurrentIndex--;

            if (g_CurrentIndex < 0)
            {
                  g_CurrentIndex = 0;
            }
      }

      if ((key == Key_Down) || (key == Key_Up))
      {
            for (i = 0 ; i < MaxLength ; i++)
            {
                  document.getElementById("oListSpan_" + (i + 1)).style.backgroundColor = "";
            }

            document.getElementById("oInput").value = document.getElementById("oListSpan_" + (g_CurrentIndex + 1)).innerHTML;
            document.getElementById("oListSpan_" + (g_CurrentIndex + 1)).style.backgroundColor = "#555555";
      }
}
</script>

</head>
<body>

<form>

<input id="oInput" type="text" onkeydown="OnKeyDownHandler(event)">
<div id="oListDiv">
      <span id="oListSpan_1">list 1</span><br/>
      <span id="oListSpan_2">list 2</span><br/>
      <span id="oListSpan_3">list 3</span><br/>
      <span id="oListSpan_4">list 4</span><br/>
      <span id="oListSpan_5">list 5</span><br/>
</div>

</form>

</body>

</html>
Avatar of narmi2
narmi2

ASKER

instead of using MaxLength=5, is there no dynamic way of detecting the size?
Yes assuming it is as simple as given.

var MaxLength = document.getElementById("oListDiv").getElementsByTagName("span").length;

you may have to modify this if you have other spans in the same div.
Avatar of narmi2

ASKER

i've left the code exactly how it is and only replaced the var MaxLength line with the new code and it does not work.   when i click the up/down arrow keys on the keyboard, nothing happens.
ASKER CERTIFIED SOLUTION
Avatar of amit_g
amit_g
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 narmi2

ASKER

Would you be interested in more points?

I hope you will be: https://www.experts-exchange.com/questions/22753494/div-tag-item-select-part-3.html