Search code examples
jquerytextfilterhoverequivalent

jQuery how to match two text strings without changing either?


Another newbie question...

The script (below) compares selected text in one div with some target text in another, then applies a style to the second div's parent. I need to change the script to be less literal---not "if A is selected, look for A"; but rather, "if Apples is selected, look for A."

So, how do you get jQuery to recognize two different text strings as being the same thing? I tried "var A = 'Apples', B = 'Bravo' [etc] ;", but then the class is added to .embox when I hover over any #menutable div.

The HTML:

    <div id="maintable">
     <div class="embox">
      content
      <div class="options">A,B,C</div>
     </div>
     <div class="embox">
      content
      <div class="options">B,F</div>
     </div>
     <!-- and about a hundred more just like these -->
    </div>

    <div id="menutable">
     <div class="optionA">Apples</div>
     <div class="optionB">Bravo</div>
     <div class="optionC">Comp</div>
     <div class="optionF">Ferengi</div>
    </div>

Current script (doesn't work):

$('#menutable div').hover(function() {
    var that = this, A = "Apples", B = "Bravo", C = "Comp", F = "Ferengi";
    $('#maintable .options').filter(function() {
        return $(this).text().indexOf($(that).text()) === -1;
    }).closest(".embox").addClass("bgtransp");
},
function() {
    $(".embox").removeClass("bgtransp");
});

Solution

  • You can try to use jQuery's inArray() method to see if the value is within an array of values that you define.

    Example:

    $.inArray($(this).html(), ['Apples', 'A', 'Orange']);
    

    In your code, check to see if the function returns something greater than -1. More info can be found in the jQuery docs linked above.