thank_you
thank_you

Reputation: 11107

button_to creates non-clickable button

I've noticed an odd behavior with button_to. I have some stylized buttons. When button_to is generated the input submit field is placed inside the button element. What ends up happening is that the inner edges of the button when clicked do not redirect the user to the new page. The user is forced to directly click on the text to redirect.

My question is, how do I fix this? I don't think CSS is a possible solution. Ideally I would like to apply the classes I pass in the button_to method to the input field. That way the input field becomes the button and not the form.

Here is the button_to method.

button_to("Click me!", 
          "/new-course",   
          {class: 'start-course-button is-normal start-course'}
         ).html_safe

Here is the html that is generated.

<form class="start-course-button is-normal start-course" method="post" action="/new-course">
  // This must be clicked below and not the form itself for there to be a redirect
  <input type="submit" value="Click me!">

  <input type="hidden" name="authenticity_token" value="secret_auth_token">
</form>

Upvotes: 0

Views: 168

Answers (2)

max
max

Reputation: 102036

button_to does not allow you to apply classes or customize the submit input.

Rather you would use form_tag to manually create the form if you need that kind of flexibility. Edited to show how it would work in a presenter.

class CoursePresenter
  def initialize(helpers)
    @h = helpers
  end

  def new_course_button
    h.form_for("/new-course") do
      h.submit_tag "/new-course",
        class: 'start-course-button is-normal start-course'
    end
  end

  private
  attr_reader :h
end

You could also use a CSS rule that targets the input element instead of the form:

.start-course-button input[type="submit"] {
  border: 2px solid black;
  padding: 10px 15px;
  background-color: pink;
}
<form class="start-course-button">
  <input type="submit" value="Click me">
</form>

Upvotes: 0

Substantial
Substantial

Reputation: 6682

Currently, you are applying styles to the form rather than the submit input inside of it. You can use a child selector to select the submit input as the form's child for a pure CSS solution.

For clarity's sake, create a new class to apply to the form. This class will select the child input of type submit.

.start-course-form input[type="submit"] {
/* button styles */
}

Then, update your helper method with the correct class.

button_to("Click me!", 
          "/new-course",   
          {class: 'start-course-form is-normal start-course'}
         ).html_safe

Note that this will not make the button a member of the start-course-button class, it will just look the same.

Upvotes: 2

Related Questions