Disable button after click in JQuery
Asked Answered
B

4

40

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();


}
Burden answered 11/5, 2014 at 21:4 Comment(3)
Do you actually have jQuery included on the page? I am asking because - although you tagged this question with jQuery - there is no jQuery being used in your code. So the answers could vary strongly depending whether you can use jQuery or not.Wadleigh
Yes, I am using JQuery. I edited my original post to show the link to JQuery. Any suggestions to disable the button after one click?Burden
Please do not use plain XHR if you are already using jQuery. It's extremely ugly to mix both.Perimorph
M
47

*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);
    });
}
Massotherapy answered 11/5, 2014 at 21:11 Comment(5)
When I added it in the load function, the button is still clickable and it stopped its function to add things to the database and change the button's text. Any particular placement for that code to make sure it works with the buttons other features?Burden
After ajax success remove disabled, answer updatedMassotherapy
I replaced the entire load function with your load function (therefore replacing AJAX for Jquery) and it still doesn't disable the button after one click (still clickable). However, it still is able to do the same thing that AJAX did, go to another page, add something to db, and change button text. If it helps, I am using a bootstrap button. Any thing I can still do?Burden
If you want to disable the button after one click then remove $('#roommate_but').prop('disabled', false);, answer updatedMassotherapy
You would get a lot more thumbs up if you make this answer more generic for the title of the question: "Disable button after click in JQuery" which shows up as top result in google. Include info on disabling directly int he answer for example/.Lullaby
Z
39

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/

Zsolway answered 11/5, 2014 at 21:10 Comment(6)
You should know when to use attr and when to use prop. This should be done using prop. You can read more about it here.Disaffect
Yeah, I think Adam is right. When I tried this code: $('roommate_but').click(function(){ $(this).attr('disabled','disabled'); }); , the button was still not disabled. So I just have to change attr to prop right? Any certain place I can place the button to get it to work? If it helps, I am actually using a bootstrap buttonBurden
-1 for using attr even though .prop() is there for years now. However, both should work.Perimorph
Note taken @PeterSmith will update. @user337712 $('roommate_but') should be $('#roommate_but')Zsolway
And how you disable a button and keep its styles because the attr "disabled" has often an opacity css rule on it.Cambrian
Have a look here. You'll need to overwrite the disabled pseudo class developer.mozilla.org/en-US/docs/Web/CSS/:disabledZsolway
D
0

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

Dreamadreamer answered 14/12, 2020 at 2:32 Comment(0)
L
-1

This code is used to accept / decline particular course which a student got as part of allotment in the college.

<script>
    $(document).on('click', '.decline', function() {
     var courseid = $(this).attr('data-id');
     $('#accept_'+courseid).prop('disabled', true);
    });

    $(document).on('click', '.accept', function() {
      var courseid = $(this).attr('data-id');
      $('#decline_'+courseid).prop('disabled', true);
    });
    function accept_decline_action(regno,coursecode,coursename,btnval){

      var url = '<?php echo site_url('home/accept_decline_status') ?>';
      $.ajax({
        url: url,
        type: 'POST',
        data: {
          regno: regno,
          coursecode: coursecode,
          coursename: coursename,
          btnval: btnval
        },
        success: function(data) {
          if (btnval == 1) {
            alert("You have accepted the course : "+coursename);
          } else {
            alert("You have declined the course : "+coursename);
          }
        }
      })
    }
</script>
<td role="cell" style="text-align: center;">
  <div>
    <button type="button" data-id = "<?= $mk['coursecode'] ?>" value = 1 
            id = "accept_<?=$mk['coursecode'] ?>" name = "accept" 
            class="btn btn-success accept"                                                             onclick="accept_decline_action('<?= $regno ?>','<?= $mk['coursecode'] ?>');"
            title="Accept" style="border-color:#4CAF50;background-color:                               #4CAF50;">&#10004
    </button>
  </div>
  <div>
    <button type="button" class="btn btn-danger decline" value=0
          data-id="<?= $mk['coursecode'] ?>" id="decline_<?= $mk['coursecode'] ?>"
          name="decline"
          onclick="accept_decline_action('<?= $regno ?>','<?= 
          $mk['coursecode'] ?>');"
          title="Decline" style="background-color:#DC143C; border-color:#DC143C">&#10008
        </button>
      </div>
    </td>
Lunatic answered 1/6, 2022 at 4:33 Comment(3)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Talkie
Your answer could be improved by adding more information on what the code does and how it helps the OP.Damondamour
@Damondamour Is it clear now?Lunatic

© 2022 - 2024 — McMap. All rights reserved.