M.Sidim
M.Sidim

Reputation: 303

clicking button only once (js)

I looked over stackoverflow and other websites, but could not find the answer I am looking for.

I have a button of sorts, and I want users to ONLY be able to click on it once. This is my javascript/jquery triggering the click event. But how can I force it so that it can ONLY be clicked once?

 $(document).ready(function () {
     //var $new_total = $('#gtotal').val();

     $('#a_is_valid').click(function () {
         if ($('#code_promo').val() == 'theCode') {
             $('#gtotal').val($('#gtotal').val() - ($('#gtotal').val() - (($('#gtotal').val() * .75))));
         }
     })
 })

Upvotes: 6

Views: 10840

Answers (4)

Gibolt
Gibolt

Reputation: 47297

Use modern JS!

const button = document.getElementById("a_is_valid");
button.addEventListener("click", function() {
    // Add one-time callback
}, {once : true});

You could also just disable the button:

button.disabled = true;

Documentation, CanIUse

Upvotes: 1

PSL
PSL

Reputation: 123749

You can use jquery .one() This will ensure that the click event happens only once.

Demo

$('#a_is_valid').one('click', function(){

        if ($('#code_promo').val() == 'theCode')
        {
          var gtot = $('#gtotal').val();
          $('#gtotal').val(gtot -(gtot -(gtot *.75)));
        }
 });

Another way is to use on() and off()

$('#a_is_valid').on('click', handleClick);

function handleClick() {
    var gtot = $('#gtotal').val();
    $(this).off('click');
    if ($('#code_promo').val() == 'theCode') {
        $('#gtotal').val( gtot - (gtot-(gtot * 0.75)) );
    }
} 

Upvotes: 6

Dom
Dom

Reputation: 40511

Why not use .one() instead of .click()?

Upvotes: 2

j08691
j08691

Reputation: 208041

Use jQuery's .one() function.

$('#a_is_valid').one('click', function(){
    if ($('#code_promo').val() == 'theCode')
    {$('#gtotal').val($('#gtotal').val()-($('#gtotal').val()-(($('#gtotal').val()*.75))));
}

Upvotes: 8

Related Questions