0

I'm trying to compare text in an unordered list to an array that I created by grabbing contents in a string then parsing it. I cannot seem to get the comparison part of my jQuery code to work where I check to see if the string lives within the array. Any suggestions?

HTML

<span id="Subjects">Commercial Law & Contracts, Immigration Law, International Law & Trade, Products Liability</span>
<ul id="SubjectList">
  <li>Administrative Law</li>
  <li>Agriculture Updates</li>
  <li>Alternative Dispute Resolution</li>
  <li>Antitrust & Trade Regulation</li>
  <li>Commercial Law & Contracts</li>
  <li>Immigration Law</li>
  <li>International Law & Trade</li>
  <li>Products Liability</li>
</ul> 

JQuery Code

var subject_passed = $('#Subjects').text();
var subjectArray = new Array();
subjectArray = subject_passed.split(',');   

$('#SubjectList li').each(function(){  
    if ($.inArray($(this).text(), subjectArray) != -1) {
        alert('hello');
    }
});
2
  • The strings in your array have spaces, you may want to trim those away. Commented Jun 26, 2012 at 21:48
  • Or var subjectArray=$('#Subjects').text().split(', '); Commented Jun 26, 2012 at 21:51

3 Answers 3

1

You could try:

var subject_passed = $('#Subjects').text();
//var subjectArray = new Array(); //not really needed as split returns new a array
var subjectArray = subject_passed.split(', '); //add a space to split

$('#SubjectList li').each(function(){  
   if ($.inArray($(this).text(), subjectArray) !== -1) { //better to use !== for comparison
     alert('hello');
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Oh snap. Thanks! That's exactly what I needed to get it to work. I hate it when I'm so close yet so far.
1

You should use $.trim() to remove the outer whitespace from the text values after the split and during the comparison:

var subject_passed = $('#Subjects').text();
var subjectArray = subject_passed.split(','); 
$.each(subjectArray, function(i, el){
    subjectArray[i] = $.trim(el);
});

$('#SubjectList li').each(function(){  
    if ($.inArray($.trim($(this).text()), subjectArray) != -1) {
        $(this).addClass('highlight');
    }
});​

See demo

1 Comment

Definitely. I did use trim in my code in the end. Thanks for the help!
0

Add a space after the comma in the following line...

subjectArray = subject_passed.split(', ');

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.