Mac Taylor
Mac Taylor

Reputation: 5148

Selecting unique values from multiples array in Jquery

I am trying to get only unique data while selecting checkbox input fields. But because of getting two values from a single input , I cannot use unique function.

jQuery('#showselected').on('click', function() {


      var selected = jQuery("#checkboxes input:checked").map(function(i, el) {
        return {
          datatitle: jQuery(this).attr('data-title'),
          dataid: jQuery(this).attr(' data-value')
        };
      }).get();
        jQuery('#rez').empty();

 
      jQuery.each(jQuery.unique(selected), function(key, value) {

        jQuery('#rez').append(value.datatitle);


      });
});
#rez {border:1px solid red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkboxes">
  <input type="checkbox" name="1" data-title="something1" data-value="someid1" />
  <label>something1</label>
  <input type="checkbox" name="2" data-title="something2"  data-value="someid2" />
  <label>something2</label>
  <input type="checkbox" name="3" data-title="something3"  data-value="someid3" />
  <label>something3</label>
  <input type="checkbox" name="4" data-title="something3"  data-value="someid3" />
  <label>something3</label>

</div>
<button id="showselected">
show selected
</button>  Select above input boxes to see what's been selected.

<div id="rez">
</div>

Upvotes: 0

Views: 152

Answers (2)

Anfath Hifans
Anfath Hifans

Reputation: 1598

You are using jQuery.unique for object value, it doesn't work.

update your last line with this code

var data = [];
jQuery.each(selected, function(key, value) {            
    if(jQuery.inArray(value.datatitle, data) < 0){
        data.push(value.datatitle);                
    }            
});
jQuery('#rez').append(data.join(', '));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

I think you can achieve this more easily with vanilla JS and Set, no need for a big library:

document.querySelector('#showselected').addEventListener('click', () => {
  const dataTitles = [...document.querySelectorAll('#checkboxes input:checked')]
    .map(checkbox => checkbox.getAttribute('data-title'));
  const titlesDeduped = [...new Set(dataTitles)];
  document.querySelector('#rez').textContent = titlesDeduped.join(', ');
});
#rez {border:1px solid red}
<div id="checkboxes">
  <input type="checkbox" name="1" data-title="something1" data-id="someid1" />
  <label>something1</label>
  <input type="checkbox" name="1" data-title="something2" data-id="someid2" />
  <label>something2</label>
  <input type="checkbox" name="1" data-title="something3" data-id="someid3" />
  <label>something3</label>
  <input type="checkbox" name="1" data-title="something3" data-id="someid3" />
  <label>something3</label>

</div>
<button id="showselected">
show selected
</button>  Select above input boxes to see what's been selected.

<div id="rez">
</div>

Upvotes: 0

Related Questions