Rushabh Shah
Rushabh Shah

Reputation: 515

jQuery simple function is not working

HTML code:

    $('.alertme').click(function(){
        alert('By selecting new image your old image will be remove');
        $(this).removeClass('alertme');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#Before a Function is executed
    <input type="file" name="efile" id="efile" style="width:100%" class="alertme">
    #After a function is executed
    <input type="file" name="efile" id="efile" style="width:100%" class="">

it still alerting me after an executing function. I didn't know why It happening? can you please help me? your help is appreciated.

Upvotes: 0

Views: 29

Answers (3)

Satpal
Satpal

Reputation: 133403

You should use .one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

$('.alertme').one('click', function(){
    alert('By selecting new image your old image will be remove');
    $(this).removeClass('alertme');
});

However better option would be to use Event Delegation using .on() delegated-events approach, when manipulation selector (like removing and adding classes).

$(document).on('click', '.alertme', function(){
    alert('By selecting new image your old image will be remove');
    $(this).removeClass('alertme');
});

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

Removing class doesn't remove the attached event handler.Remove the event handler by using off() method.

$('.alertme').click(function(){
    alert('By selecting new image your old image will be remove');
    $(this).off('click').removeClass('alertme');
});

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Traverse again for check whether the dom element or class is removed or not Using through event delegation.

$(document).on('click', '.alertme', function(){
    alert('By selecting new image your old image will be remove');
    $(this).removeClass('alertme');
});

Upvotes: 0

Related Questions