简体   繁体   中英

JS issue with dropdown menu and state selection

Here's the fiddle: https://jsfiddle.net/6aevjxkx/38/

In the dropdown menu, if you select Nebraska, you'll see a school location from Washington state, which shouldn't appear.

The issue I believe is that the script is searching the ENTIRE td section for any matching state initial. In the case of the school from Washington, it has "NE" in the address, causing it to appear when you choose Nebraska from the dropdown.

With that said, how can the script be updated so it can only search for a matching state within the div that has a class "state"? Or if there's another solution, my ears are wide open.

Thanks ahead!

Code of the script

$('select#stateCollege').change( function(e) { 
   var letter = $(this).val();
     if (letter === 'ALL') {
         $ ('table.event tr').css('display','inline-block');
     } else {
         $('table.event tr').each( function(rowIdx,tr) {
             $(this).hide().find('td').each( function(idx, td) {
                 if( idx === 0 || idx === 1) {
                     var check = $(this).text();
                     if (check && check.indexOf(letter) > 0) {
                        $(this).parent().css('display','inline-block');
                    } 
                 }
       });             
    });
   }             
});

Something like the following works:

$('table.event tr').each(function(rowIdx, tr) {
    var row = $(this).hide();
    var state = row.find('.state').text().trim();
    if (state === letter)
        row.css('display', 'inline-block');
});

Updated demo: https://jsfiddle.net/6aevjxkx/42/

That is, hide the current row, then find the .text() of its .state element, .trim() that, then rather than .indexOf() just use === to compare to the value in the rather confusingly named letter variable.

Note that there was no point to using .each() on your td elements given that there is only one td in each row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM