Text Input field with dynamic placeholder

Hi,

In my html.eex template form, I have a text_input form input and would like to pass to the placeholder a value based on some other field from the form (previously saved before form is rendered). I would like to do something like the following - have a :username field with a placeholder of the :first_name field value, but the placeholder variable is not recognised here:

<%= form_for @changeset, @action, fn f -> %>
  <%= text_input f, :username, placeholder: :first_name %>
  ... 
<% end %>

Is this possible to do with the text_input macro or do I need to use the tag macro? Thanks!

If You know the value of first_name, pass it as a variable in the controllerā€¦

:first_name is only an atom, pass it, and use it as @first_name.

If You want to use conditional rendering on the same formā€¦ You will need some JS skillā€¦ or LiveView, or Drab, or any server side libs that can potentially update DOM.

1 Like

Thanks, that makes complete sense - I was thinking that :first_name would auto-magically be available when the form ā€˜is loadedā€™

If you are wanting :first_name to pull from a key on your changeset/whatever named first_name then you can always do this:

<%= form_for @changeset, @action, fn f -> %>
  <%= text_input f, :username, placeholder: input_value(f, :first_name) %>
  ... 
<% end %>

And that will compile the value in as the placeholder. If you want it to update ā€˜on the pageā€™ then thatā€™s a Javascript thing, so either a some javascript, drab, live_view, etcā€¦ :slight_smile:

2 Likes

Thanks! Very helpful indeed, input_value is easier than passing variable into a controller

1 Like