weixin_33690963 2011-02-03 20:05 采纳率: 0%
浏览 26

jQuery选择选项取消选择

I am trying to deselect a select option element with jQuery. Here is my scenario:

I have 3 select options:
[ Select 1 ]
[ Select 2 ]
[ Select 3 ]

Scenario: Select 1 is prefilled with data from an ajax call. So Select 1 has opt 1, opt 2, opt 3, etc.
When you select an option from Select 1, it fills Select 2 with data, and when you select from Select 2 it fills Select 3, and so on.

Depending on what you select, it puts the values from those ":selected" options and apply to a variable called "url".

So in the case that you only select "Select 1":
url = 'search/for/this/select1/'

In th case that you select "Select 1" and "Select 2"
url = 'search/for/this/select1/select2/

And so on.

This is the way im writing the jQuery code:

var url = 'search/for/this';  
if(element1.is(':selected')) {
  url += element1.val();    
  // makes url = 'search/for/this/select1val/';  
     if(element2.is(':selected')) {  
        url += element1.val();    
         // makes url = 'search/for/this/select1val/select2val/';  
        if(element3.is(':selected')) {  
            url += element1.val();    
            // makes url = 'search/for/this/selectval1/select2val/select3val/';  

         }  
    }  
}  

The problem is, this requires that I de-select the next options after the previous one was selected, but since there is data that is filled in, it seems to automatically return true when it passes through the ":selected" condition check in the code example above. Any thoughts on how to accomplish this functionality? If I am not making my issue clear. Please requested more details and I will add them in. Thanks -Chris-

  • 写回答

1条回答 默认 最新

  • weixin_33716941 2011-02-03 20:20
    关注

    It looks like you're adding a lot of complexity to what should otherwise be a reasonably simple task.

    As you've described it, you want to get the values of all selected values from your drop-down lists and concatenate them into a URL.

    The jQuery $.map() function is an excellent fit for this example. Try the following code:

    var searchTerms = $('option:selected').map(function() {
      return $(this).val();
    }).get().join('/');
    
    url = 'search/for/this/' + searchTerms;
    

    You would then execute this code when you needed to actually get the selected values (e.g. when your search is submitted, for example. You may also want to get the option's text rather than its actual value, in which case the code would change to return $(this).text();

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题