text_field_tag(name, value = nil, options = {}) public

Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.

Options

  • :disabled - If set to true, the user will not be able to use this input.

  • :size - The number of visible characters that will fit in the input.

  • :maxlength - The maximum number of characters that the browser will allow the user to enter.

  • :placeholder - The text contained in the field by default which is removed when the field receives focus. If set to true, use the translation found in the current I18n locale (through helpers.placeholder.<modelname>.<attribute>).

  • Any other key creates standard HTML attributes for the tag.

Examples

text_field_tag 'name'
# => <input id="name" name="name" type="text" />

text_field_tag 'query', 'Enter your search query here'
# => <input id="query" name="query" type="text" value="Enter your search query here" />

text_field_tag 'search', nil, placeholder: 'Enter search term...'
# => <input id="search" name="search" placeholder="Enter search term..." type="text" />

text_field_tag 'request', nil, class: 'special_input'
# => <input class="special_input" id="request" name="request" type="text" />

text_field_tag 'address', '', size: 75
# => <input id="address" name="address" size="75" type="text" value="" />

text_field_tag 'zip', nil, maxlength: 5
# => <input id="zip" maxlength="5" name="zip" type="text" />

text_field_tag 'payment_amount', '$0.00', disabled: true
# => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />

text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
# => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
Show source
Register or log in to add new notes.
August 26, 2008
6 thanks

Prototype hinted_text_field application_helper

Place this in your helper. It will show a message inside the text box and remove it when someone clicks on it. If they don’t enter a value when they leave the field it’ll replace the message. (Requires javascript :defaults).

def hinted_text_field_tag(name, value = nil, hint = "Click and enter text", options={})
  value = value.nil? ? hint : value
  text_field_tag name, value, {:onclick => "if($(this).value == '#{hint}'){$(this).value = ''}", :onblur => "if($(this).value == ''){$(this).value = '#{hint}'}" }.update(options.stringify_keys)
end

# inside form_for example

hinted_text_field_tag :search, params[:search], "Enter name, brand or mfg.", :size => 30  
# => <input id="search" name="search" onblur="if($(this).value == ''){$(this).value = 'Enter name, brand or mfg.'}" onclick="if($(this).value == 'Enter name, brand or mfg.'){$(this).value = ''}" size="30" type="text" value="Enter name, brand or mfg." />