0

I already have a jQuery .on() function in which click event is passed on a button.

I want to restrict user from clicking button more than 1 but i don't want to alter current function instead write new function

$('button').on('click', function() {
    alert('hi');
});

$('button').click(function(event) {
    var count = 0;
    count = count + 1;
    if (count > 1) {
        event.preventDefault();
        console.log('dont call alert');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Click Me !</button>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Jay
  • 397
  • 1
  • 5
  • 16

3 Answers3

1

I think you are looking for something like following.

$('button').on('click', function () {
    alert('hi');
});


var isCliked = true;
$('button').click(function () {
    $('button').off('click');

    isCliked && $('button').click(function() {
        console.log('dont call alert');
        isCliked = false;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
    Click Me !
</button>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

You can use jQuery .one() method:

$('button').one('click', function() {
    alert('hi');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Click Me !</button>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • I already have a .on() function written in another file and i dont have access to that file ... so want to override it – Jay May 30 '16 at 15:42
0

JQuery off() method remove event handler of element. You can remove click event of button when it clicked. Using this work, button click event fired only once.

$("button").click(function(event){
    alert();
    $(this).off("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>
Mohammad
  • 21,175
  • 15
  • 55
  • 84