用javascript选择标签状态检查?

时间:2015-10-01 05:28:05

标签: javascript jquery html dom

我现在有两个选择标签我想要的是,只有一个应该从两个选择标签中选择一个用户应该只选择一个,如果用户从两个标签中选择那么它应该只显示一个错误应该被选中

我在用什么

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;
}

请帮助纠正代码谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>
&#13;
&#13;
&#13;