Home > Net >  Change button class if value true or false
Change button class if value true or false

Time:05-12

I have two buttons with opposite states "Freeze" and "Unfreeze". When the database record is in a false state, I want to show the button "Freeze" below:

<%= form.submit "Freeze", class: 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded' %>

When the database record is in a true state, I want to show the "Unfreeze" button here:

<%= form.submit "Unfreeze", class: 'bg-white-500 hover:bg-white-700 text-white font-bold py-2 px-4 border border-blue-700 rounded' %>

I was thinking something like this, but I am not sure (also, this does not have the text change...):

<tr class=<%= dbrecord.frozen ? "bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded" : "bg-white-500 hover:bg-white-700 text-white font-bold py-2 px-4 border border-blue-700 rounded" %>>

CodePudding user response:

Why don't you just make it very simple?

<% if dbrecord.frozen? %>
  <%= form.submit "Unfreeze", class: 'bg-white-500 hover:bg-white-700 text-white font-bold py-2 px-4 border border-blue-700 rounded' %>
<% else %>
  <%= form.submit "Freeze", class: 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded' %>
<% end %>

IMHO this is easy to read and understand.

CodePudding user response:

Not my favorite way of doing this, but you can do:

<%= form.submit(dbrecord.frozen ? 'Unfreeze' : 'Freeze', class: 'bg-white-500 hover:bg-white-700 text-white font-bold py-2 px-4 border border-blue-700 rounded') %>

However, please be wary of the toggle pitfall. Often these types of toggle buttons are implemented with a toggle in code which is error-prone. Make sure you perform the task asked, not just toggling the value. For example, imagine the value of the DB field is frozen: true and the page displays Unfreeze. Then the underlying value is changed to frozen: false perhaps by the same user in another browser tab. Now the original page will still show the button with Unfreeze text. The user then forgets what they've done before, and want to make sure the record is unfrozen, so they click the original Unfreeze button on the original page. If it is setup to just toggle the DB value, it will now be incorrectly set to frozen: true. Make sure that you perform the task asked, not just performing some toggle. I've seen this done incorrectly so many times.

  • Related