rails check_box_tag set checked with default value

后端 未结 6 1414
说谎
说谎 2021-02-18 14:38

I currently have a rails check_box_tag call that looks like

check_box_tag #{name}

I want to include a checked attribute, which I know I can do

相关标签:
6条回答
  • 2021-02-18 14:43

    Just wanted to update this. The third parameter for check_box_tag is a boolean value representing the checked status.

    check_box_tag name, value, true
    
    0 讨论(0)
  • 2021-02-18 14:44

    If you pass in a value of "1" to the value field, it will pass-on the value of the real state of the checkbox, regardless of the checked default value:

    is_checked = <default boolean>
    
    check_box_tag :show_defaults, '1', is_checked
    

    (now always reflects user input)

    0 讨论(0)
  • 2021-02-18 14:50

    If anyone have column type boolean then look at this. is_checked? will be default boolean value. It worked for me.

    <%= hidden_field_tag :name, 'false' %> <%= check_box_tag :name, true, is_checked? %>

    0 讨论(0)
  • 2021-02-18 14:59

    If you want the checkbox to be checked, then

    check_box_tag name, value, {:checked => "checked"} 
    

    otherwise

    check_box_tag name, value
    
    0 讨论(0)
  • 2021-02-18 14:59

    check_box_tag(name, value = "1", checked = false, options = {})

    Examples:

    check_box_tag 'receive_email', 'yes', true
    # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
    
    check_box_tag 'tos', 'yes', false, class: 'accept_tos'
    # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
    
    check_box_tag 'eula', 'accepted', false, disabled: true
    # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
    

    api.rubyonrails.org

    0 讨论(0)
  • 2021-02-18 15:09

    There are no ways to do it directly. But the check_box_tag implementation is trivial, you can monkey patch it or create own helper.

    Original implementation:

      def check_box_tag(name, value = "1", checked = false, options = {})
        html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
        html_options["checked"] = "checked" if checked
        tag :input, html_options
      end
    
    0 讨论(0)
提交回复
热议问题