Judy M.
Judy M.

Reputation: 243

Multiple div selection onclick

I have multiple divs with their id's, and onclick i store the id of the div in an input value, but it only takes one id, i want to have multiple selection and store all the selected div id's in the same input, here is my code:

  function storeId (el) {
     $('input').val(el.id);
  }
div{
background-color:red;
height: 50px;
width: 50px;
margin-bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1" onclick="storeId(this);">
</div>

<div id="div-2" onclick="storeId(this);">
</div>

<div id="div-3" onclick="storeId(this);">
</div>

<div id="div-4" onclick="storeId(this);">
</div>

<input>

Upvotes: 3

Views: 3677

Answers (3)

veratti
veratti

Reputation: 570

You have two options based on your requirements:

  1. Append newly clicked id's to the existing value of your input.
  2. Push newly clicked id's into an array which is used to build the value of your input.

Option 1

function storeId (el) {
   var currentValue = $('input').val();
   $('input').val(currentValue + ', ' + el.id);
}

(Or with newer syntax)

function storeId (el) {
   const currentValue = $('input').val();
   $('input').val(`${currentValue}, ${el.id}`);
}

Option 2

var storedIds = [];
function storeId (el) {
   var index = storedIds.indexOf(el.id);
   if (index === -1) {
      storedIds.push(el.id);
   } else {
      storedIds.splice(index, 1);
   }

   $('input').val(storedIds.join(', '));
}

Edit: Only the array example above checks if the id being stored has already been stored or not.

Upvotes: 1

Hanif
Hanif

Reputation: 3795

Please try it:

    function storeId (el) {
        if ($('input').val().indexOf(el.id) >= 0){
            $('input').val($('input').val().replace(el.id + ",", ""));
            return
        }
        $('input').val($('input').val() + el.id + ",");
    }

Upvotes: -1

Scott Marcus
Scott Marcus

Reputation: 65815

Instead of setting the input's value directly, store the id in an array and then upon each click, update the input with the array's contents.

Also, don't use inline HTML event attributes. There are many reasons not to use this ancient technique that just will not die.

let ids = [];
$("div").on("click", function(){
  // If the id is not already in the array, add it. If it is, remove it
  ids.indexOf(this.id) === -1 ? ids.push(this.id) : ids.splice(ids.indexOf(this.id),1);
  $('input').val(ids.join(", ")); // populate the input with the array items separated with a comma
});
div{
  background-color:red;
  height: 50px;
  width:50px;
  margin-bottom: 15px;
  display:inline-block; /* Just for the SO space */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
<div id="div-4"></div>

<input>

Upvotes: 4

Related Questions