0

I have this each() which collects all checked checkboxes with parameter data-is-rate = 1

 $('input[data-is-rate="1"]:checked').each(function(){
     console.log($(this).attr('data-id'));
 });

From this, I'm getting every data-id

111
222
333

So is there any way to compare them? The IDs are not unique and can be the same and I need to check.

So if data-id recurs, it should return an error.

For example, if the output is like this, it should return an error.

111
222
111

If the output is like this, there should be no error because the values are unique

111
222
333

How can I compare these?

2 Answers 2

1

something like this maybe helps, when error do what ever needs to be done...

var ids = [];
$('input[data-is-rate="1"]:checked').each(function(){
  console.log($(this).attr('data-id'));
  
  if(ids.includes($(this).attr('data-id'))) {
      console.log(' E R R O R !');
  }
  
  ids.push($(this).attr('data-id'));
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-is-rate="1" type="checkbox" data-id="111" checked="checked">111
<input data-is-rate="1" type="checkbox" data-id="111" checked="checked">111
<input data-is-rate="1" type="checkbox" data-id="222" checked="checked">222
<input data-is-rate="1" type="checkbox" data-id="333" checked="checked">333

if data-id="111" is not checked twice there is no error

var ids = [];
$('input[data-is-rate="1"]:checked').each(function(){
  console.log($(this).attr('data-id'));
  
  if(ids.includes($(this).attr('data-id'))) {
      console.log(' E R R O R !');
  }
  
  ids.push($(this).attr('data-id'));
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-is-rate="1" type="checkbox" data-id="111" checked="checked">111
<input data-is-rate="1" type="checkbox" data-id="111" >111
<input data-is-rate="1" type="checkbox" data-id="222" checked="checked">222
<input data-is-rate="1" type="checkbox" data-id="333" checked="checked">333

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

Comments

1

You can try something like this

var unique = {};
$('input[data-is-rate="1"]:checked').each(function(){
    if (unique[$(this).attr('data-id')]) {
        // Duplicate data-id, handle error
        alert('Duplicate data-id' + $(this).attr('data-id'));
    } else {
        unique[$(this).attr('data-id')] = 1;
    }
});

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.