如何从<option>获取值并使用</option>

时间:2014-10-27 11:41:43

标签: javascript jquery html

现在我有以下代码:

<form class="demo">
<select>
    <option selected>Selecione sua cidade</option>
    <option value='JP'>João Pessoa - PB</option>
    <option value='outros'>Outros</option>
</select>
</form>

我需要什么:

当访问者点击下拉菜单并选择一个选项时,他们会转到http://www.example.com 每个选项都会转到不同的地址。

值=&#39; JP&#39;转到example.com

值=&#39;片尾&#39;转到example2.com

谢谢!

编辑: 我正在使用它                         

<script>
$('.demo select').change(function(){
 window.location.href="http://www.example.com";
 });
</script>
</head>

但仍然无效,以及如何使用打开不同的链接:

选择选项1 = www.example1.com

选择选项2 = www.example2.com

4 个答案:

答案 0 :(得分:2)

为什么不尝试这样的事情

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option selected>Selecione sua cidade</option>
    <option value='www.example1.com'>João Pessoa - PB</option>
    <option value='www.example2.com'>Outros</option>
</select>

答案 1 :(得分:1)

将url作为select中的值,并调用onchange函数:

<form class="demo">
<select onchange="go(this.value);">
    <option selected>Selecione sua cidade</option>
    <option value='http://someurl.com'>João Pessoa - PB</option>
    <option value='http://another.com'>Outros</option>
</select>
</form>

<script>
function go(url){
    window.location.href=url;
}
</script>

答案 2 :(得分:1)

您可以使用Jquery val()函数来检查选择了哪个值。

form:

<form class="demo">
<select>
   <option selected>Selecione sua cidade</option>
   <option value='http://example.a'>João Pessoa - PB</option>
   <option value='http://example.b'>Outros</option>
</select>
</form>

<script>
$(function (){
  $('.demo select').change(function(){
    window.location.href = $(this).val();
  }
});
</script>

答案 3 :(得分:0)

请尝试这样的事情:

<form class="demo">
<select id='drop'>
    <option selected>Selecione sua cidade</option>
    <option value='JP'>João Pessoa - PB</option>
    <option value='outros'>Outros</option>
</select>
</form>

<script>
 $("#drop").change(function () {
    var res = this.value;
    if(res=='JP')
    {
            document.location.href = "http://example.com";
    }
    else if(res == 'outros')
    {
      document.location.href = "http://example2.com";
    }
    });
</script>