Solution 1 :

Use selectedOptions property of element on submit event. 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>

Problem :

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
. 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.
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 -->

Comments

Comment posted by Vaibhav

on which event you want to validate…submit?

Comment posted by joshua

yes when submit button is pressed

Comment posted by joshua

thanks vaibhav but actually the problem is that if minimum 3 options is selected than only it must submit not if we have selected only 1 or 2

Comment posted by Vaibhav

Oh! you just need to add if condition and decide whether to submit or not. Plz check I’ve updated the code

By

Leave a Reply

Your email address will not be published. Required fields are marked *