how to get limited multiselect values from the list box

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

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>
function getValue()
  var x=document.getElementById("sel");
  result = '';
  alert("length is"+x.options.length);
  for (var i = 0; i < x.options.length; i++) {
	  result = result +"," +x.options[i].value;
	  //selcustid = selcustid + ",'" + document.adcrptform.custid.options[i].value + "'";				
  alert("result is "+result);
<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>
<input type="button" value="Get Value" onclick="getValue()"/>

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael VasilevskySolutions ArchitectCommented:
I think you were close. Please try the below.


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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
srikoteshAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.