JQuery从文本中选择选项

时间:2014-06-12 10:04:23

标签: javascript jquery coffeescript

我有以下html:

<select class="select optional form-control" id="search_form_handover_location" name="search_form[handover_location]"><option value="">Wybierz miejsce odbioru</
    <option value="Gdańsk">Gdańsk</option>
    <option value="Gdańsk">Gdańsk, Lotnisko</option>
    <option value="Ożarowice">Katowice, Lotnisko</option>
</select>    
<select class="select optional form-control" id="search_form_return_location" name="search_form[return_location]"><option value="">Wybierz miejsce zwrotu</option>
      <option value="Gdańsk">Gdańsk</option>
      <option value="Gdańsk">Gdańsk, Lotnisko</option>
      <option value="Ożarowice">Katowice, Lotnisko</option>
</select>

在我的应用程序中,我使用JQuery自动完成第二次选择。因此,当您在第一个选择“Gdańsk”时,它也会在第二个选择中选择它。我的coffeescript代码如下所示:

$ ->
  $('#search_form_handover_location').change ->
    location = $("option:selected", this).val()
    $('#search_form_return_location').val(location)

现在我通过使用每个选项的值来做这件事。但是现在我想通过使用not value而不是text来做到这一点。因此,在第一次选择时,您选择“Gdańsk,Lotnisko”,它将自动选择具有相同文本的第二个选择选项。有没有可能解决我的问题?

3 个答案:

答案 0 :(得分:3)

您可以使用此行获取文字,随心所欲地使用它...

$("#search_form_handover_location:selected").text();

答案 1 :(得分:1)

var location=$("#search_form_handover_location:selected").text();

$("#search_form_return_location option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == location; 
}).attr('selected', true);

答案 2 :(得分:1)

试试这个:首先获取文本表单下拉列表并在第二个下拉列表中找到它。

$ ->
  $('#search_form_handover_location').change ->
     locationTxt = $("option:selected", this).text();

        $('#search_form_return_location option').each(function(){
           if($(this).text()==locationTxt)
               $(this).prop('selected',true);
           else
               $(this).removeProp('selected'); 
       });