-2

I am working on a website and come into some issues. I am relatively new to javascript and I am having a hard time with this button that I have. Here is the code I have now

<!-- Html school selector -->
<select id="schools"></select>

<script>
var schools = ["School one", "School two", School three", "And so on"];

var sel = document.getElementById('schools');
for(var i = 0; i < schools.length; i++) {
 var opt = document.createElement('option');
opt.innerHTML = schools[i];
opt.value = schools[i];
sel.appendChild(opt);
}

</script>

This makes the selected item the name of the select box, and is not what I am trying to acheive.

I got the idea for this from this link Javascrit array. I am trying to take a list of schools and have them in a drop down list which can then be selected and made active, I have tried everything I can think of. I have tried using bootstrap buttons like so

 <div class="btn-group">
  <button class="btn btn-mini">Action</button>
   <button class="btn btn-mini dropdown-toggle" data-toggle="dropdown">
   <span class="caret"></span>
</button>
 <ul class="dropdown-menu">
  <li>School one</li>
  <li>School two</li>
  <li>School three</li>
 </ul>
</div>

But these Li's aren't selectable and cannot add them to an array or an id! All I am trying to do is make the li's selectable and then either use their value or id and add them to a sentence and array, Sorry if this is long or extreme but any help is appreciated!

Destry
  • 228
  • 1
  • 12

1 Answers1

0

The following code shows all of the array items in an unordered list and allows you to select them. Then shows the array item value in an alert box when the 'select' button is clicked.

<html>

  <head>

  </head>

  <body>

    <select id="schools"></select>

    <button id='select-button'>Select</button>

  </body>

      <script>
      var schools = ["School one", "School two", "School three", "And so on"];

      var sel = document.getElementById('schools');

      for(var i = 0; i < schools.length; i++) {
        var opt = document.createElement('option');
        opt.innerHTML = schools[i];
        opt.value = schools[i];
        sel.appendChild(opt);
      };

      var button = document.getElementById('select-button');

      button.addEventListener('click', function() {
        alert(sel.options[sel.selectedIndex].value)
      });

    </script>


</html>

For simplicity I have embed the javascript directly into the HTML, however it can easily be extracted out. The main thing I changed was to put the javascript into the body rather than the head.

Is this what you were looking for?

Phil Brockwell
  • 456
  • 5
  • 22