简体   繁体   English

如何在具有多个属性的 select 标记中选择必要的选项

[英]How to make option selected necessary in select tag with multiple attribute

i want to make a condition that would allow a user to select minimum 3 options from select tag with multiple attribute but the options are coming dynamically from input tag after comma(,) is entered.我想创建一个条件,允许用户从具有多个属性的 select 标记中使用 select 至少 3 个选项,但选项在输入逗号(,)后动态来自输入标记。 for eg if user type hello and then type comma(,) the value hello will be displayed on option tag.so how can i make my option selected and with minimum of 3 option selected.例如,如果用户键入 hello 然后键入 comma(,) 值 hello 将显示在选项标记上。所以我怎样才能使我的选项被选中并至少选择 3 个选项。 here is my code这是我的代码

var skills = document.querySelector('#skills');
var skillhave = document.querySelector('#skill');
var skillshaving = [];

skills.addEventListener('keyup', function(event) {
  if (event.keyCode === 188) {

    if (this.value.length < 2) {
      alert("skill required");
      this.value = "";
    } else {
      var skill = this.value.substring(0, this.value.length - 1);
      skillshaving.push(skill);
      this.value = "";
      //reloadskills();
      addSkills(skill);
    }
  }
});
function addSkills(skill) {       
  var opt = document.createElement('option');
  opt.value = skill.toUpperCase();;
  opt.innerHTML = skill.toUpperCase();;
  opt.selected = true;
  skillhave.appendChild(opt);
}
<input type="text" class="form-control" placeholder="Enter skill" name="skills" id="skills"> <!--for entering skills via text -->

<select name="" id="skill" multiple></select>
<!--for diplaying it in option tag -->

Use selectedOptions property of element on submit event.在提交事件上使用元素的selectedOptions属性。 See following snippet请参阅以下片段

 function submit() { const multiSelect = document.querySelector('#multi-select'); if (multiSelect.selectedOptions.length > 2) { console.log('process submit'); } else { console.log('Please select atleast 3 options'); } }
 <select id="multi-select" multiple> <option>2</option> <option>4</option> <option>6</option> <option>8</option> </select> <button onclick="submit()">Submit</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM