Limiting the number of selected values

Asked

Viewed 470 times

0

How can I change the script below to work in the following precise way that it performs the following limit the number of marks or can select in the max 2 items of the list if it exceeds the maximum allowed value of an alert message.

<html>
  <head>
    <title>Seleção de Itens</title>
    <script type="text/javascript">
      //Array que guarda a ordem em que os elementos foram inseridos
      var listCheckedOptions = [];

      function addToList(checkObj, outputObjID)
      {
        //Remove do array caso o elemento já esteja inserido
        if (listCheckedOptions.indexOf(checkObj.value) >= 0) {
          listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj.value), 1);
        } else { //Adiciona casojá esteja inserido
          listCheckedOptions.push(checkObj.value);
        }

//        alert(listCheckedOptions); //debug para verificar os elementos inseridos
        document.getElementById(outputObjID).value = ""; //Limpa o textarea
        document.getElementById(outputObjID).value = listCheckedOptions.join('\r\n'); //Adiciona no textarea

        return;
      }
    </script>
  </head>
  <body>
    <form name="myform">
      <input type="checkbox" name="fruit[]" value="Oranges" onClick="addToList(this, 'txt1')"><font color="#808080">Oranges</font><br>
      <input type="checkbox" name="fruit[]" value="Apples"  onClick="addToList(this, 'txt1')"><font color="#808080">Apples</font><br>
      <input type="checkbox" name="fruit[]" value="Grapes"  onClick="addToList(this, 'txt1')"><font color="#808080">Grapes</font><br>
      <textarea rows="4" cols="10" name="txt1" id="txt1" style="color:#808080"  readonly></textarea>
    </form>
  </body>
</html>

2 answers

2


To check how many elements there are in an array just use array.length

Within the else where you add the element in array, could do something like:

if(listCheckedOptions.length >= 2){
    alert("Máx 2 Elemenos selecionados"); 
    checkObj.checked = "";
    return;
}

Exp:

var listCheckedOptions = [];

function addToList(checkObj, outputObjID){
  //Remove do array caso o elemento já esteja inserido
  if (listCheckedOptions.indexOf(checkObj.value) >= 0) {
    listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj.value), 1);
  }else{
    if(listCheckedOptions.length >= 2){ 
      alert("Máx 2 Elemenos selecionados");
      checkObj.checked = "";
      return;
    }
    listCheckedOptions.push(checkObj.value);
  }

  document.getElementById(outputObjID).value = ""; //Limpa o textarea
  document.getElementById(outputObjID).value = listCheckedOptions.join('\r\n'); //Adiciona no textarea

  return;
}
<input type="checkbox" name="fruit[]" value="Oranges" onClick="addToList(this, 'txt1')"><font color="#808080">Oranges</font><br>
<input type="checkbox" name="fruit[]" value="Apples"  onClick="addToList(this, 'txt1')"><font color="#808080">Apples</font><br>
<input type="checkbox" name="fruit[]" value="Grapes"  onClick="addToList(this, 'txt1')"><font color="#808080">Grapes</font><br>
<textarea rows="4" cols="10" name="txt1" id="txt1" style="color:#808080"  readonly></textarea>

Edit

I added the functionality mentioned by @read to de-select the element when the amount of elements is higher than the determined.

  • That’s what I wanted to thank you for your help.

  • Only a complement as I can in the case type when checking the item in the checkbox make appear a number in check order because in the case instead of textarea I will be using hidden field have to make numbers appear in the checkbox items when they mark appear at positions where they were marked in case of selecting the second take the position of the first and so on ?

  • When so @Rodrigo, you can and must create a new question, because this new doubt runs too far from the context of the original question, there is no problem in this case

  • Grateful for the answer I am then asking a new question with the code obtained from this answer.

1

You can add checkObj.checked = false; to Marcelo Bonifazio’s answer. To prevent another element from being chosen.

The function would be:

var listCheckedOptions = [];

function addToList(checkObj, outputObjID){
  if(listCheckedOptions.length >= 2){
    alert("Máx 2 Elemenos selecionados"); 
    checkObj.checked = false;
    return;
  }
  //Remove do array caso o elemento já esteja inserido
  if (listCheckedOptions.indexOf(checkObj.value) >= 0) {
    listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj.value), 1);
  }else{
    if(listCheckedOptions.length >= 2){ alert("Máx 2 Elemenos selecionados"); return;}
    listCheckedOptions.push(checkObj.value);
  }

  document.getElementById(outputObjID).value = ""; //Limpa o textarea
  document.getElementById(outputObjID).value = listCheckedOptions.join('\r\n'); //Adiciona no textarea

  return;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.