dvmac01
dvmac01

Reputation: 489

Click Event IF statement

I'm trying create a button handler which will look at an if statement to determine which function to run.

I've created three separate button handlers which work fine (based on IDs) but I'd like to roll them into one by selecting by class then filtering by ID. I can't quite get the syntax right though. The code is below, thanks in advance for any assistance.

$(".btnSort").click(function() {
    console.log('button clicked');
var divList = $(".listing").toArray();

divList.sort(function(a, b){
    //sort by alpha
    if ($(this).hasId('#alphBtn')) {
        return $(a).find('.hotel').text() > $(b).find('.hotel').text() ? 1 : -1; ;
    }
    //sort by price
    else if ($(this).hasId('#priceBtn')) {
        return +$(b).find('.price').data('price') - +$(a).find('.price').data('price');
    }
    //sort by rating
    else {
        return +$(b).find('.stars').data('sort') - +$(a).find('.stars').data('sort');
    }
});

$("#container").html(divList);

$('.btnSort').removeClass('active');
$(this).addClass('active');
});
});

Here is the fiddle:http://jsfiddle.net/dvmac/h58exqsu/13/

Upvotes: 1

Views: 3305

Answers (2)

jyrkim
jyrkim

Reputation: 2869

Here is sth that I would try. I changed $(".btnSort").click handler to save the button id into clickedButtonId variable, that is later used for comparison. I haven't tested the code but I would give it a go.

  $(".btnSort").click(function() {

    var clickedButtonId = $(this).attr("id");
    //console.log("clicked button id: " + clickedButtonId);

    var divList = $(".listing").toArray();

    divList.sort(function(a, b){
        if (clickedButtonId === 'alphBtn') {
            return $(a).find('.hotel').text() > $(b).find('.hotel').text() ? 1 : -1; ;
        }
        //sort by price
        else if (clickedButtonId === 'priceBtn') {
            return $(b).find('.price').data('price') - +$(a).find('.price').data('price');
        }
        //sort by rating
        else {
            return $(b).find('.stars').data('rating') - +$(a).find('.stars').data('rating');
        }
    });

    $("#container").html(divList);

    $('.btnSort').removeClass('active');
    $(this).addClass('active');
    });
});

Upvotes: 1

rodrigogq
rodrigogq

Reputation: 1953

Instead of creating if statements, can't you just use and appropriate selector in jquery for querying these buttons?

Examples:

 $('#test') // query for ellements that has id="test"
 $('.test') // query for ellements that has class="test"
 $('#test .test') // query for child ellements of id="test" that has class="test"
 $('.test #test') // query for child ellements of class="test" that has id="test"
 $('#a, #b') // query for child ellements with id="a" or id="b"

You just have to create your selector correctly and put any handler you want, like .on("click", function () {});

Upvotes: 0

Related Questions