Pressing the button only once (js)

I looked at stackoverflow and other sites, but could not find the answer I'm looking for.

I have a sort button, and I want users ONLY to click on it once. This is my javascript / jquery triggering a click event. But how can I get it to be clicked ONLY 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))));
         }
     })
 })
+5
source share
4 answers

Use the jQuery function .one().

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

You can use jquery. This ensures that the click event occurs only once. . one()

$('#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 and on() ()

$('#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)) );
    }
} 
+5
source

.one() .click()?

+2

JS!

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

:

button.disabled = true;

, CanIUse

0

All Articles