使用javascript选择标签状态检查

Select tag status check with javascript?

本文关键字:状态 检查 标签 选择 javascript 使用      更新时间:2023-09-26

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

我在用什么

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

请帮忙更正代码谢谢!

问题是你在分配而不是比较。用==代替=

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>

您所需要做的就是在一个条件下检查两个值,如下所示:

 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