SamuraiJack
SamuraiJack

Reputation: 5539

How to prevent user from clicking button more than once?

I am trying to prevent user from clicking the submit button more than once. I tried a number of things which are on SO for similar issue.

Like for example :

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js">
    $('<% =btnUpload.ClientID %>').click(function () { this.disabled = true });
</script>

I also tried..

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js">
  $("form").submit(function() {
    $(this).submit(function() {
        return false;
    });
    return true;
  });
</script>

and also tried...on master page

<form onsubmit="if(submitted) return false; submitted = true; return true">

But to no use.. I am still able to click on button more than once.

Markup:

<asp:Button ID="btnUpload" runat="server" class="blue-button" 
CssClass="ButtonText"OnClick="btnUpload_Click"
 OnClientClick="if (!confirm('Are you sure that you want to Save entered details ?'))
 return false;return doCustomValidate(event,true);"
     Text="Save" />

Also note that I am using master page so

Upvotes: 3

Views: 3598

Answers (4)

Jake 404
Jake 404

Reputation: 171

Add a disabled attribute to it.

$('#<% =btnUpload.ClientID %>').click(function () {
    $(this).prop("disabled", true);
});

Upvotes: 2

CJ Ramki
CJ Ramki

Reputation: 2630

Set one count variable in javascript. initialize it's value as 0. In .click() event listener check the condition. If it is 0, allow to execute the code and increase count by 1. Else, return false.

var count = 0;
$('#<% =btnUpload.ClientID %>').click(function () {
    if (count == 0) {
        count++;
        return true;
    } else {
        return false;
    }
});

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

You missed # in your id prepend it before <% =btnUpload.ClientID %> like,

$(function(){
    $('#<% =btnUpload.ClientID %>').click(function () {
        this.disabled = true;
    });
});

If you want to add click event once only then use one() like,

$(function(){
    $('#<% =btnUpload.ClientID %>').one('click',function () {
        // your code on click event
    });
});

If, your id changes(Clientid changes after render) then try to use class selector like,

$(function(){
    $('.ButtonText').click(function () {
        this.disabled = true;
    });
});

Upvotes: 1

HamidRaza
HamidRaza

Reputation: 650

If you want the user to click on the button just once, use .one() to attach event.

jquery url : http://api.jquery.com/one/

Upvotes: 2

Related Questions