simonfoust
simonfoust

Reputation: 131

Trigger click event for an element with a class that was added by a previous event

Here is my HTML:

<div class="filter msg-1">
    <p>Filter has been applied</p>
    <span class="button">Apply Another Filter</span>
</div>
<div class="filter" id="filterSet1">
    <form>
        <select class="select1" required>
            <option value="">---Filter By---</option>
            <option value="OptionOne">Option One</option>
        </select>
        <select class="select2" required>
            <option value="">---Select---</option>
            <option value="Isequalto">Is equal to</option>
            <option value="Isnotequalto">Is not equal to</option>
        </select>
        <input class="text1" type="text" required>
        <input type="submit" value="Apply Filter" class="button">
    </form>
</div>

Here is my JavaScript:

$('.accordion .filter').bind('keyup', function() { 
    var select1Length = $(".select1").length;
    var select2Length = $(".select2").length;
    var text1Length = $(".text1").length;
    if (select1Length > 0 && select2Length > 0 && text1Length > 0) {
       $('.accordion .filter .button').addClass('apply');
    }
});
$('#filterSet1 .button.apply').click(function(){
    $('#filterSet1').hide('fast');
    $('.accordion .filter.msg-1').show('fast');
});

So what I'm trying to do is make sure all three form fields are filled out, and if so, then the submit button gets a class "apply". That works, so far so good.

Then, when a user clicks the button and it has that class (.button.apply) another event is triggered. Namely, I'm just trying to hide the container with the form and then show a container with a message. The problem is, the code for that second event isn't working because on page load there IS no element with .apply

Upvotes: 0

Views: 513

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use event delegation as your selector needs to be evaluated dynamically

$('#filterSet1').on('click', '.button.apply', function(){
    $('#filterSet1').hide('fast');
    $('.accordion .filter.msg-1').show('fast');
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You should use:

$('#filterSet1 .button.apply').live('click',function(){
$('#filterSet1').hide('fast');
$('.accordion .filter.msg-1').show('fast');
});

Or if you have jquery library 1.7 and further:

$('#filterSet1 .button.apply').on('click',function(){
$('#filterSet1').hide('fast');
$('.accordion .filter.msg-1').show('fast');
});

Upvotes: 1

Related Questions