2016-03-01 112 views
0

我有兩個選擇元素與一些選項。我想要做的就是用jquery處理這個問題,以便只有當選項有值時纔可以獲取它們的值。多個選擇元素 - 從jQuery中選擇一個選項時處理

<div class="panel-heading"> 
     <select id="loading-by-tag"> 
      <option value="" disabled selected> -- Select Subject --</option> 
      <option value="value1">Selection 1</option> 
      <option value="value2">Selection 2</option> 
     </select> 

     <select id="loading-by-sub-tag"> 
      <option value="" disabled selected> -- Select Subject --</option> 
      <option value="value1">Selection 1</option> 
      <option value="value2">Selection 2</option> 
     </select> 
    </div> 

如果我想用一個select元素只處理我用.on('change', function()與選擇元素和它的作品,但有多個選擇元素我怎麼能做到這一點。

回答

3

您應該檢查selectedIndex是不是0您的所有select元素。

$(document).on('change', 'select', function() { 
 
    var allChanged = true; 
 

 

 
    // check if there is any other select element which was not changed 
 
    $('select').each(function() { 
 
     if (this.selectedIndex == 0) { 
 
      allChanged = false; 
 
     } 
 
    }); 
 

 
    // if all select elements have been changed 
 
    if (allChanged) { 
 
     alert('BOTH CHANGED'); 
 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="panel-heading"> 
 
     <select id="loading-by-tag"> 
 
      <option value="" disabled selected> -- Select Subject --</option> 
 
      <option value="value1">Selection 1</option> 
 
      <option value="value2">Selection 2</option> 
 
     </select> 
 

 
     <select id="loading-by-sub-tag"> 
 
      <option value="" disabled selected> -- Select Subject --</option> 
 
      <option value="value1">Selection 1</option> 
 
      <option value="value2">Selection 2</option> 
 
     </select> 
 
    </div>

+0

非常感謝你:) –

1

只是一個側面說明,使用.filter()

$('select').change(function() { 
    var m = $(this).siblings('select').addBack(); 
    var n = m.filter(function(){ 
    return $(this).val() == null && $(this) 
    }); 
if (!n.length) alert('both selected') 
}); 

DEMO

+0

很好的解決。謝謝:) –

+0

不客氣的隊友 –

相關問題