Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a button more elegantly

Tags:

I have on one of my views the following razor code:

@if (item.PMApproved != true) {                     <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" />                 }                 else {                     <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" disabled="disabled" />                 } 

Pretty rough. Basically I want to disable the button under a certain condition as you'd be able to work out from the code. What would be a more desirable way of doing this?

like image 661
AnonyMouse Avatar asked Apr 15 '12 21:04

AnonyMouse


People also ask

How do I make a button disabled?

The disabled attribute is a boolean attribute. When present, it specifies that the button should be disabled. A disabled button is unusable and un-clickable. The disabled attribute can be set to keep a user from clicking on the button until some other condition has been met (like selecting a checkbox, etc.).

Why you shouldn't gray out disabled buttons?

Gray is often used to communicate a low priority button (e.g., cancel buttons). When they see a gray button, they won't know for sure if it's disabled unless they click it. This uncertainty and unpredictability is not an optimal user experience. When making your button transparent, adjust the opacity, not the color.


2 Answers

A markup-centric solution aided by a new extension method:

public static class HtmlExtensions {    public static HtmlString DisabledIf(this HtmlHelper html, bool condition)    {       return new HtmlString(condition ? "disabled=\"disabled\"" : "");    } } 

In your views, reuse out the wazoo:

<button type="reset" @Html.DisabledIf(someCondition)>Clear Fields</button> 

Nicely reusable, and the rendered markup is very clean with regards to whitespace:

<button type="reset" disabled="disabled">Clear Fields</button> 
like image 102
David Grant Avatar answered Oct 24 '22 13:10

David Grant


I don't know what language you're using, but you might be able to move your if statement closer to the actual different between the two lines:

<input type="button" class="btnresetinvoice button" value="Reset"        data-invoiceid="@item.InvoiceId"        @{ if(item.PMApproved != true) {               @:disabled="disabled"          } } /> 
like image 21
Brendan Long Avatar answered Oct 24 '22 14:10

Brendan Long