Reputation: 303
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
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;
Upvotes: 1
Reputation: 123749
You can use jquery .one() This will ensure that the click event happens only once.
$('#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