2015-10-01 3 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

Смежные вопросы