ZUH.
ZUH.

Reputation: 195

How do I set one event handler for two elements?

At the moment the second element is only ever changed after the first one is.

Is it possible to use the same event handler on both elements if they're both drop down box's and keeping both elements selected while constructing the right URL no matter which element receives the event??

$(function(){
   var url = '';
    $('#search_region').change(function () {
        url = $(this).val();
        window.location.hash = url;
         console.log(window.location.hash);
    });

    $('#search_categories').change(function () {
       if(url !==''){
         window.location.hash = url+"&"+$(this).val();
       }
        console.log(window.location.hash);
    });

});

Upvotes: 1

Views: 101

Answers (3)

gurvinder372
gurvinder372

Reputation: 68393

At the moment the second element is only ever changed after the first one is.

In that case you can append the hash value of category to region

$('#search_region, #search_categories').change(function () {
   var regURL =  $('#search_region').val();    
   var catURL =  $('#search_categories').val();    

   window.location.hash += regURL + ( catURL ? ("&" + catURL) : "" );
   console.log(window.location.hash);
});

Upvotes: 4

Vinod Selvin
Vinod Selvin

Reputation: 379

$(function(){

    $('#search_region, #search_categories').change(function () {

         ...Your logic

    });

});

for more info: https://api.jquery.com/multiple-selector/

Upvotes: -1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

$(function() {

  const changeHash = () => if ($('#search_region').val())
    window.location.hash = 
        $('#search_region').val() + "&" + $('#search_categories').val();

  $('#search_region').change(changeHash);
  $('#search_categories').change(changeHash);

});

Upvotes: 2

Related Questions