4

I am wanting to write some jQuery code that converts a HTML

<select> 
  <option> Blah </option> 
</select>

combo box into something (probably a div) where selecting an item acts the same as clicking a link.

I guess you could probably use JavaScript to handle a selection event (my JavaScript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.

How can I go about this?

4 Answers 4

8

The simple solution is to use

$("#mySelect").change(function() {
  document.location = this.value;
});

This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option.

Sign up to request clarification or add additional context in comments.

Comments

2

I'm not sure where you want to link to when you click the Div, but given something like this perhaps would work:

<select id="mySelect">
  <option value="1">Option 1</option>
  <option value="2">Option 2</options>
</select>
<div id="myDiv"/>

and the following JQuery creates a list of <div> elements, a goes to a URL based on the value of the option:

$("#mySelect option").each(function() {
    $("<div>" + $(this).text() + "</div>").appendTo($("#myDiv")).bind("click", $(this).val(), function(event) {
        location.href = "goto.php?id=" + event.data;
    });
});
$("#mySelect").remove();

Does this do what you want?

Comments

0

This bit of javascript in the 'select':

onchange="if(this.options[this.selectedIndex].value!=''){this.form.submit()}"

It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.

Comments

0

If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to:

$("[id*='COMMON_NAME']").change(function() {
    document.location = this.value;
});

And have your select boxes be named accordingly:

<select id="COMMON_NAME_001">...</select>
<select id="COMMON_NAME_002">...</select>

This creates a onchange event for all IDs containing "COMMON_NAME" to do a redirect of the <option> value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.