Amin Poursaied Amin Poursaied - 2 months ago 6
jQuery Question

search in items with jquery and after pressing enter page will redirect to selected item link

i make a search plugin with jquery contains function
now i want to add a feature that when user press enter key in the search input after searching the item page redirect to the selected item href
this is my code



jQuery.expr[':'].contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};


jQuery(function($) {

$('input[name="search"]').keyup(function(){

var searchterm = $(this).val();

if(searchterm.length >1) {
var match = $('.item_name:contains("' + searchterm + '")');
var nomatch = $('.item_name:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.addClass('uk-hidden');

} else {
$('.item_name').removeClass('uk-hidden');
$('.item_name').removeClass('selected');
}

});

var statematch = $('.item_name:contains("استان")');
statematch.remove().parent();
});

.uk-hidden{
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="uk-search">
<input class="uk-search-field" type="search" name="search" placeholder="search here">
</div>
<div class="ad-city-list">
<div class="item_name"><a href="tehran.html">Tehran</a></div>
<div class="item_name"><a href="istanbul.html">Istanbul</a></div>
<div class="item_name"><a href="tabriz.html">Tabriz</a></div>
</div>





now how i can do that ?

Answer

Try this:

 jQuery.expr[':'].contains = function(a,i,m){
            return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
        };


        jQuery(function($) {

            $('input[name="search"]').keyup(function(){ 

                var searchterm = $(this).val();

                if(searchterm.length >1) {
                    var match = $('.item_name:contains("' + searchterm + '")');
                    var nomatch = $('.item_name:not(:contains("' + searchterm + '"))');             
                    match.addClass('selected');
                    nomatch.addClass('uk-hidden');


                } else {
                    $('.item_name').removeClass('uk-hidden');
                    $('.item_name').removeClass('selected');                
                }

            });

            var statematch = $('.item_name:contains("استان")');
            statematch.remove().parent();


              $(document).keypress(function(e) {
                       if(e.which == 13) {
                          var url1 = $('.item_name.selected:not(.uk-hidden) a').attr('href');
                          $(window.location).attr('href', url1);
                       }
                     });
        });