简体   繁体   中英

jQuery trigger click on first element with specific property

I am making a search for my dropdown menu and I have some problems. When you search my dropdown by typing on keyboard the elements with your search change background color. Now what I would like it is to trigger click event when you search and press enter after finding country you want (if there is more then one country enter should select first one). I'm using background color to find elements that I need for enter key. Here is my attempt to achieve this:

function enterTest() {

    $('.dropdown').on('show.bs.dropdown', function() {
        $(document.body).on('keypress', addClick);
    })

    $('.dropdown').on('hide.bs.dropdown', function() {
        $(document.body).off('keypress', addClick);
    })

    function addClick (e) {
        var key = e.which;
        var $background = $('.dropdown-menu ul li a').css('background-color');

        if (key == 13 ) {
            if ($background == 'rgba(255, 171, 0, 0.15)') {
                $('.dropdown-menu ul li a:eq(0)').click();
            }
        }
    }
}

$('.dropdown-menu ul li a:eq(0)').click(); When I use this part it always selects first element from the all a elements, but what I need is to select first element with rgba(255, 171, 0, 0.15) . I have tried to use eq() like this: $(this).eq(0).click() but this also didn't work. I have also tried to do something like this:

    if (key == 13 ) {
        $background.each(function (i) {
            if ($background == 'rgba(255, 171, 0, 0.15)') {
                $(this).click();
                return;
            }
        })
    }

but this also didn't work.
Is there a way to trigger click event to first element with specific color ? Can anyone help me solve this ? Here is the codepen with example of my search without the function above https://codepen.io/Karadjordje/pen/MEBjRY

$('.dropdown-menu ul li a').filter(function(){
    $bg = $(this).css('background-color');
    if ($bg === 'rgba(255, 171, 0, 0.15)') {
        return true;
    }
}).eq(0).click();

The .filter part filters your results down to whatever you return true for, which in this case is the background color. .eq(0) gets those filtered results and only gives back the first one, and obviously .click() clicks it.

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