how to get limited multiselect values from the list box

srikotesh
srikotesh used Ask the Experts™
on
Hi Experts,

Below is the list box having list of values
i can do multi select from the list box
i have to show an alert if the user choosen more than 5 values from the list
alert-->please choose only 5 values.
finally i have to see the list of selected items in an var called result

example
if user choose vals as 45,123,456,
i have to assign those values to result  var with comma separted as shown in above lline

<!DOCTYPE html>
<html>
<script>
function getValue()
{
  var x=document.getElementById("sel");
  result = '';
  alert("length is"+x.options.length);
  for (var i = 0; i < x.options.length; i++) {
     if(x.options[i].selected){
      alert(x.options[i].value);	  
	  result = result +"," +x.options[i].value;
	  //selcustid = selcustid + ",'" + document.adcrptform.custid.options[i].value + "'";				
  }  
  }
  alert("result is "+result);
}
</script>
</head>
<body>
<select multiple="multiple" id="sel">
  <option value="123">123</option>
  <option value="456">456</option>
  <option value="789">789</option>
  <option value="234">234</option>
  <option value="45">45</option>
  <option value="765">765</option>
  <option value="435">435</option>
  <option value="321">321</option>
  <option value="123">123</option>
</select>
<input type="button" value="Get Value" onclick="getValue()"/>
</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Solutions Architect
Commented:
I think you were close. Please try the below.

JSFiddle

getValue = function() {
 const x = document.getElementById("sel")
 const result = [];
 
  for (let i=0; i < x.length; i++) {
    if (x[i].selected) result.push(x[i].innerText);
  }

  if (result.length > 5) {
  	alert("Please choose only 5 values.");
  } else {
  	alert("Result is "+ result.join(", "));
  }
}

Open in new window

Author

Commented:
THANKS

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial