Toggle disabled attribute on input field

Hello,

I need to toggle disabled attribute on an input field and have the following code:

def is_disabled(true, attrs), do: [{:disabled, true} | attrs]
def is_disabled(_, attrs), do: attrs

<%= form_for :price_form, "#", [phx_change: :price_change], fn f -> %>
     <%= text_input f, :price, is_disabled(true, [value: @total_price]) %>

The input field will be shown correctly - it will be disabled and the toggling will work. The problem is however that in the appropriate callback function, the form will just ignore that input field:

  def handle_event("price_change", params, socket) do
     IO.inspect params["price_form"]

The IO.inspect shows the following:

%{
  "comment" => "",
  "invoicing_entity" => "1",
}

All input fields are shown except for the :price one.

I confirmed that when I take out the toggling part, everything works fine.

Any help is highly appreciated!

Disabled fields do not have their value sent. If you want to send the value you probably want to create a hidden field when the text input is disabled with the same name that holds the value.

Or, alternatively, use readonly instead of disabled if you want to show the input (and submit it) but prevent users to change its value.

A readonly text input can be focused and is submitted as part of the form, but cannot be changed manually by the user.

2 Likes

Thanks for your response @benwilson512

I don’t want to send the value of the disabled field but the value of that field when it is enabled.
So, initially the field is disabled, but if the user clicks on some other field, it will be enabled and the user can type in new value. It is that new value I would like to send.

1 Like