2015-10-01 93 views
0

我有兩個選擇標籤現在我想要的是,只有一個應該從兩個選擇標籤中選擇一個用戶應該只選擇一個,如果用戶從兩個標籤中選擇,那麼它應該顯示錯誤,只有一個應該選擇選擇標籤狀態檢查與JavaScript?

我所用

var $institution=document.getElementById('institutionselect').value; 
var $section=document.getElementById('sectionselect').value; 

if($institution.selectedIndex = 0 && $section.selectedIndex = 0){ 
    alert('please select one amongst two'); 
    return false; 

}else if($institution.selectedIndex = null && $section.selectedIndex = null){ 
    alert('please select one amongst two'); 
    return false; 
} 

請糾正碼幫忙,謝謝!

回答

1

問題是你要分配,而不是比較。使用==而不是=

if($institution.selectedIndex = 0 && $section.selectedIndex = 0) 

而且更新該行,以使用去除.value.selectedIndex

var $institution=document.getElementById('institutionselect'); 
var $section=document.getElementById('sectionselect'); 

一個例子:

var check = function() { 
 
    var $institution = document.getElementById('institutionselect'); 
 
    var $section = document.getElementById('sectionselect'); 
 
    if ($institution.selectedIndex == 0 && $section.selectedIndex == 0) { 
 
    alert('please select one amongst two'); 
 
    return false; 
 
    } 
 
};
<select id='institutionselect'> 
 
    <option>Select</option> 
 
    <option>Item 1</option> 
 
    <option>Item 2</option> 
 
</select> 
 
<select id='sectionselect'> 
 
    <option>Select</option> 
 
    <option>Item 1</option> 
 
    <option>Item 2</option> 
 
</select> 
 
<button onclick="check();">Check</button>

1

所有你需要做的是檢查這兩個值在一個條件,像這樣:

var $institution = document.getElementById('institutionselect').value; 
var $section  = document.getElementById('sectionselect').value; 

// if both variable have values 
if ($institution && $section){ 
    alert('please select one amongst two'); 
    return; 
} 

// do something here 

DEMO