-1

I need to be able to check for an exact match in my list using jQuery.

I need to be able to tell if it an exact match exists, not if a sub-string match exists.

if ($('.validValuesListMain ul li:contains('+val+')').length ) {
    notImportedCount++;
} else {                    
    importCount++;
    $('.validValuesListMain ul').append('<span class="deleteValid" title="Delete Autofix">X</span><li class="validTag">'+val+'</li>');
}

Process Flow

For example when a user types in 'John Doe' if 'John Doe' does exist, then error. If a user types 'John Doe' and in the list there is 'John Do' then this is okay as it's not an exact match.

Pseudo Code

If (John Doe) not exact match (John Do) {
    alert('no duplicates found');
} else {
    alert('duplicates found');
}
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Kieron606
  • 613
  • 3
  • 13
  • 28

1 Answers1

1

There's no selector in jquery can do this you need to loop through the elements using for example filter() or each(), check example bellow :

var new_entry = "John Doe";
var duplicate = false;

$('.validValuesListMain ul li').filter(function() {
    if( $(this).text()==new_entry )
        duplicate = true;
})

if (duplicate){
    alert('duplicates found');
} else {
    alert('no duplicates found');
}

Hope this helps.


Snippet

$('body').on('input','input',function(){
  var new_entry = $(this).val();
  var duplicate = false;

  $('.validValuesListMain ul li').filter(function() {
    if( $(this).text()==new_entry )
      duplicate = true;
  })

  if (duplicate){
    alert('duplicates found');
  } else {
    alert('no duplicates found');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placehoslder="filter here"/>
<div class="validValuesListMain">
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
  </ul>
</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Thanks for the useful answer but this doesn't work as duplicate will always be false as when you are setting it in the filter it is out of scope, also remember this needs to be checked after the enter key has been pressed. – Kieron606 May 16 '16 at 10:03
  • You're welcome, but that will work 100% and there's no out of scope here you could see the variable defined before filter, check please working snippet in my update. – Zakaria Acharki May 16 '16 at 11:01
  • 1
    Then problem come from the fiddle and note the code, **[Updated fiddle](https://jsfiddle.net/rpg6m9b1/6/)** : first you should add jquery to the fiddle second you should give your main div the class `validValuesListMain` as you mentioned in the question then it simply work fine. – Zakaria Acharki May 16 '16 at 11:59