赣西狠人
赣西狠人

Reputation: 342

Linking to other page based on datalist option

Now I have a datalist with a few options, and I want to link to other page when one of them is selected. Below is my first attempt, in which I tried to directly add a hyper link to the option label. But it did not seem to work.

    <input type="text" name="my-input" list="my-list">
    <datalist id="my-list">
    <option value="a"><a href="http://stackoverflow.com/questions"></a>a</option>
    <option value="b"><a href="http://stackoverflow.com/questions"></a>b</option>
    <option value="c"><a href="http://stackoverflow.com/questions"></a>c</option>
    </datalist>

Then I also tried to specify the onclick event of each option, and jump to other page accordingly, but still failed. So is it possible to achieve this using datalist?

Upvotes: 4

Views: 4959

Answers (1)

Ahs N
Ahs N

Reputation: 8366

This is how I would do it:

$(document).ready(function() {
  $("[list='my-list']").on("input propertychange", function() {
    window.location = $("#my-list option[value='"+$("[list='my-list']").val()+"']").find("a").attr("href")
  });
});

Here is the CodePen demo

Note that the page is blank after redirect because SO does not allow cross domain origin. Check your console to see the redirect attempt.

Upvotes: 2

Related Questions