0

I have this form set up as a basic drop down menu that goes to whichever link / option is selected immediately, but I was wondering if it was possible / how to append all of the options in JavaScript in a separate file? I am just starting to learn JavaScript, so any explanation would be exceptionally helpful too. Thank you for your time!

<form name="nav">
    <select name="navigation" onChange="window.document.location.href=this.options[this.selectedIndex].value;" value="GO" style="width:100%;">
        <option selected="selected">go to...</option>
        <option value="index.html">PROJECTS</option>
        <option value="about.html">ABOUT</option>
    </select>
</form>
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
user3106225
  • 87
  • 1
  • 6
  • 1
    http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery – Shahe Dec 16 '13 at 06:25

3 Answers3

1

Here's a demo to start with

The HTML

<form id="my-form">
  <select name="navigation">
    <option>Go to...</option>
  </select>
</form>

Now we just encode the navigation options in a JSON object and dynamically load them into the select element

var navigation = [
  {"title": "PROJECTS", url: "index.html"},
  {"title": "ABOUT", url: "about.html"}
];

var select = document.getElementById("my-form").navigation;

for (var i=0, option; i<navigation.length; i++) {
  option = document.createElement("option");
  option.value = navigation[i].url;
  option.innerText = navigation[i].title;
  select.appendChild(option);
}

select.addEventListener("change", function(event) {
  window.location.href = select.value;
});

This is vanilla JavaScript, but you could use jQuery if you like that better.

maček
  • 76,434
  • 37
  • 167
  • 198
  • This is working really well for me and does exactly what I need. The only issue is that it doesn't append the options in Firefox. – user3106225 Dec 21 '13 at 21:37
0

I dont how much You know JS or which framework (server, client) You are using. But regardless of that You could for example try to built navigation here using content sent from the server.

For instance You generate the request in the client side, that You want to load navigation dynamically into this select and on a success ajax You populate the dropdown.

Write more about the frameworks You are using. Is the JS pure JS or perhaps jQuery.

BTW. The code You've posted isn't exactly HTML5-way of building the dropdown. Go to HTML5 Form elements and take a look on the very first example with

<input list="browsers">
kornicameister
  • 305
  • 1
  • 15
0

You can do this:

var str = '<option selected="selected">go to...</option>'+
          '<option value="index.html">PROJECTS</option>'+
          '<option value="about.html">ABOUT</option>';
$('#formId').html("");
$('#formId').append(str);

Hope this helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124