2011-08-08 61 views
0

我試圖檢查$('select option:selected')。val();包含某些單詞,如果是,則重定向到某個頁面。jQuery使用:contains()來搜索選項的值:選中

這裏是我的HTML:

<select name="people_view" id="people_view"> 
    <optgroup label="People Categories"> 
     <option value="category_1">Members</option> 
     <option value="category_2">Connections</option>  
    </optgroup> 
    <optgroup label="Groups"> 
     <option value="group_1">Group 1</option> 
     <option value="group_2">Group 2</option> 
     <option value="group_3">Group 3</option> 
    </optgroup> 
    <optgroup label="Custom Views"> 
     <option value="view_1">Test People View</option> 
    </optgroup> 
</select> 

這裏是我的JS:

if ($('#people_view option:selected:contains("category_")')) { 

     categoy_id = $(this).val().replace('category_', ''); 
     window.location.href = admin_url + 'people/?category=' + categoy_id; 

    } else if ($('#people_view option:selected:contains("group_")')) { 

     group_id = $(this).val().replace('group_', ''); 
     window.location.href = admin_url + 'people/?group=' + group_id; 

    } else if ($('#people_view option:selected:contains("view_")')) { 

     view_id = $(this).val().replace('view_', ''); 
     window.location.href = admin_url + 'people/?view=' + view_id; 

    } 

是沒可能同時使用兩個選擇(例如:選擇:包括())。或者我只是做錯了什麼?

感謝您的幫助!

回答

2
$('#people_view').change(function() { 
    var val = $(':selected', this).val(); 
    var arr = val.split('_'); 
    console.log(admin_url + 'people/?' + arr[0] + '=' + arr[1]); // this for your visual of the url. delete this line 
    //window.location.href = admin_url + 'people/?'+ arr[0] +'=' + arr[1]; // uncomment this line 
}); 
1

更改此:

if ($('#people_view option:selected:contains("category_")')) { 

要:

if ($('#people_view option:selected:contains("category_")').length) { 

等。

你也可以這樣做

$('option:selected').filter(':contains(blah), :contains(blah2)') 

所以都在一起,這將是:

if ($('#people_view option:selected').filter(':contains(category_), :contains(group_), :contains(view_)').length) 
//...