0

When clicking on checkboxes I'm trying to get id of that checkbox and put it in array so I can properly show it in data-id attribute. So once i click on checkbox that id should be added or removed in data-id attribute of div with class block Here is the jsfiddle https://jsfiddle.net/chille1987/5g28uoqk/25/

<input type="checkbox" id="121asa31" class="user">
<input type="checkbox" id="121fdfd31" class="user">
<input type="checkbox" id="1213fd1" class="user">
<input type="checkbox" id="121jh31" class="user">

<div class="block" data-id="">
  Some Content 
</div>

$('.user').on('click', function() {
    id = $(this).attr('id');
    users = $('.block').data('data-id')
    if($(this).is(':checked')) {
        users.push(id);
        users.toString();
        $('.block').attr('data-id', users);
    } else {
        index = users.indexOf(id);
        users.splice(index, 1);
        $('.block').attr('data-id', users);
    }
});

Expected results should look like

<div class="block" data-id="121asa31, 121jh31"></div>

3 Answers 3

1

You can make this a lot easier by wrapping your <input> elements in a <form> tag and listen for the change event on the form. A change event occurs whenever the user checks or un-checks a checkbox. Whenever a change happens use .serializeArray() to get an array with all the values that are checked in your form. Then use the .map() method of the array to only get the id value from each checked input and join the values with .join() to turn the array into a string with the ids separated by comma's. And with the result set the data-id value with the new string.

$('.user-form').on('change', function(event) {
  var $form = $(this);
  var data = $form.serializeArray();
  var users = data.map(({ value }) => value).join(', ');
  $('.block').attr('data-id', users);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="user-form">
  <input type="checkbox" name="user" value="121asa31" class="user">
  <input type="checkbox" name="user" value="121fdfd31" class="user">
  <input type="checkbox" name="user" value="1213fd1" class="user">
  <input type="checkbox" name="user" value="121jh31" class="user">
</form>

<div class="block" data-id="">
  Some Content 
</div>

Example with users and groups

function filterIdsByName(name, data) {
  return data
    .filter(item => item.name === name)
    .map(({ value }) => value)
    .join(', ');
}

$('.user-form').on('change', function(event) {
  var $form = $(this);
  var data = $form.serializeArray();
  var groups = filterIdsByName('group', data);
  var users = filterIdsByName('user', data);
  $('.block-groups').attr('data-group-id', groups);
  $('.block-groups').html(`Group ids: ${groups}`);
  $('.block-users').attr('data-user-id', users);
  $('.block-users').html(`User ids: ${users}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="user-form">
  <input type="checkbox" name="user" value="121asa31" class="user">
  <input type="checkbox" name="user" value="121fdfd31" class="user">
  <input type="checkbox" name="user" value="1213fd1" class="user">
  <input type="checkbox" name="user" value="121jh31" class="user">
  <input type="checkbox" name="group" value="1213fd1" class="check group">
  <input type="checkbox" name="group" value="121jh31" class="check group">
</form>

<div class="block-users" data-user-id="">
  Some Content 
</div>

<div class="block-groups" data-group-id="">
  Some Content 
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Interested solution. I could also have inputs with different classes(user and group). So i'm thinking if i changed user checkbox data-id-user is added/removed based on checked/unchecked state and if group is checked then data-id-group is added/removed jsfiddle.net/chille1987/n2cL3doh/9
Well, if you use the name attribute for users and groups, then you can filter the data in the .map() method by either users or groups if you need to. I'll add a demonstration.
I've added a function in the script which allows you to filter the id's based on the value of the name attribute on the inputs.
1

What you are looking for is a list not an array. For checkboxes, you want to use change not click as click can trigger unintentionally.

You can always set a variable called users to be an array and simply modify that array and then use that to set the data-id.

I also updated the function to run on load and to be much simpler.

function save_users(){
   var users = [];
    
    $(".user:checked").each(function(){
       users.push($(this).attr('id'));
    });
    
   users = users.join(",");
    
   $('.block').attr('data-id', users);
}

$('.user').on('change', function() {
    save_users();
});

save_users();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="121asa31" class="user">
<input type="checkbox" id="121fdfd31" class="user">
<input type="checkbox" id="1213fd1" class="user">
<input type="checkbox" id="121jh31" class="user" checked>

<div class="block" data-id="">
  Some Content 
</div>

2 Comments

Looks good but still I can have something like this on initial and if you click on unchecked checkbox the one that is checked will be removed. jsfiddle.net/chille1987/n2cL3doh/2
@DenisOmerovic, I have updated my answer. It now includes a function that runs on load as well as on change of the checkboxes. You also just need to loop through the checked boxes and can ignore the ones that aren't checked.
0

Javascript Vanilla Solution

let checkboxes = document.getElementsByClassName("user");
for (let i = 0; i < checkboxes.length; i++) {
  checkboxes[i].addEventListener("change", checkBoxChanged);
}
let checkedIDs = [];

function checkBoxChanged() {
  if (event.target.checked) {
    checkedIDs.push(event.target.id);
  } else {
    if (checkedIDs.indexOf(event.target.id) > -1) {
      checkedIDs.splice(checkedIDs.indexOf(event.target.id), 1)
    }
  }
  console.log(checkedIDs);
  let myDiv = document.getElementsByClassName("block")[0];
  myDiv.setAttribute("id", checkedIDs);
}
<input type="checkbox" id="121asa31" class="user">
<input type="checkbox" id="121fdfd31" class="user">
<input type="checkbox" id="1213fd1" class="user">
<input type="checkbox" id="121jh31" class="user">

<div class="block" data-id="">
  Some Content
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.