murday1983
murday1983

Reputation: 4016

Disable Button OnClick

I have an asp.net application which is a random generator and I want my button to disable and stay disabled when clicked.

I have tried adding OnClientClick="this.disabled = true;" to my <asp:button> and also tried adding the following to my onclick in the code behind BtnDecideForMe.Attributes.Add("onclick", "this.disabled=true;"); but none of these work.

Not bothered how its done as long as it's clean and does the job.

HTML

<div class="col-sm-2">
    <asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
</div>

On_Click Event

protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
    List<string> Eat = new List<string>();
    Eat.Add("Chinese Buffet");
    Eat.Add("Harvester");
    Eat.Add("Frankie & Benny's");
    Eat.Add("Hungry Horse");
    Eat.Add("Blaize");
    Eat.Add("Chiquito");
    Eat.Add("Cafe Football");
    Eat.Add("Nando's");

    Random Place = new Random();
    int Places = Place.Next(0, Eat.Count);
    txtDestination.Text = Eat[Places];
  //BtnDecideForMe.Enabled = false;
}

I don't really want to use BtnDecideForMe.Enabled = false; as it loses my bootstrap styling and don't really want to apply a whole lot of css.

Upvotes: 0

Views: 3174

Answers (4)

murday1983
murday1983

Reputation: 4016

Not want I wanted to do but I decide to duplicate code (not the best I no but it does the job), anyway answer below:

<% if (txtDestination.Text == "")
{%>
    <asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
<%}
else
{ %>
    <button class="btn btn-success" disabled>Decided</button>
<%} %>

Upvotes: 0

Moe
Moe

Reputation: 1599

Using JQuery, you can achieve that using below code snippet. This will disable the button when the form is posted and remove the disabled attribute once completed.

  $(document).on('invalid-form.validate', 'form', function () {
        var button = $(this).find('input[type="submit"]');
        setTimeout(function () {

            button.removeAttr('disabled');
        }, 1);
    });
    $(document).on('submit', 'form', function () {
        var button = $(this).find('input[type="submit"]');
        setTimeout(function () {

            button.attr('disabled', 'disabled');
        }, 0);
    });

Upvotes: 0

Jonathan Bowman
Jonathan Bowman

Reputation: 1646

I haven't looked into asp.net much, but if you're just trying to use jQuery to disable a button on click can you target it as you would any other element and use something like this?

  $(document).on("click", "#your-buttons-id", function() {
    $(this).prop("disabled", true);
  });

http://codepen.io/jonathanrbowman/pen/jbZVyL#0

Upvotes: 0

Vidhyardhi Gorrepati
Vidhyardhi Gorrepati

Reputation: 682

You can use the below code in button click event.

BtnDecideForMe.Enabled = false;

Upvotes: 1

Related Questions