Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button after click in JQuery

My button uses AJAX to add information to the database and change the button text. However, I wish to have the button disabled after one click (or else the person can spam the information in the dataabase). How do I do this?

HTML

<button class="btn btn-lg btn-primary" id='roommate_but' onclick='load(<?php echo $user_id;?>)'><span class="glyphicon glyphicon-plus"></span> Add Person</button>

Javascript / AJAX / JQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

function load(recieving_id){                                    
    if (window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    } else{
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){  
            document.getElementById("roommate_but").innerHTML =  xmlhttp.responseText;


        }

    }

xmlhttp.open('GET','include.inc.php?i=' + recieving_id, true);

xmlhttp.send();


}
like image 687
user3377126 Avatar asked May 11 '14 21:05

user3377126


People also ask

How do I disable the button after clicking?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.

How disable submit button until form is filled jQuery?

$('#enabled'). click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button'). removeAttr('disabled'); } else { $('#submit-button'). attr('disabled', 'disabled'); } });


2 Answers

*Updated

jQuery version would be something like below:

function load(recieving_id){     $('#roommate_but').prop('disabled', true);     $.get('include.inc.php?i=' + recieving_id, function(data) {         $("#roommate_but").html(data);     }); } 
like image 169
Manoj Yadav Avatar answered Sep 18 '22 12:09

Manoj Yadav


You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true); 

I have made a simple example http://jsfiddle.net/4gnXL/2/

like image 38
kplates Avatar answered Sep 21 '22 12:09

kplates