Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a button work as a link in erb?

<%= link_to 'New Post', new_post_path %> 

This produces link to new_post_path. Previously i used <input type="submit" class="new" name="Addlist" value="Add New" /> which resembled like a button. So how can i make the link look like button in erb?

like image 703
usr Avatar asked Aug 16 '12 11:08

usr


3 Answers

Take a look at button_to. In summary it will be simmilar to this:

<%= button_to "New Post", { :action => "new" }, :method => :get %>

Although be aware, this method accepts the :method and :confirm modifiers described in the link_to documentation. If no :method modifier is given, it will default to performing a POST operation. You can also disable the button by passing :disabled => true in html_options. If you are using RESTful routes, you can pass the :method to change the HTTP verb used to submit the form.

like image 26
waldyr.ar Avatar answered Oct 22 '22 21:10

waldyr.ar


@Ryan's answer is good but sadly fails html validation http://validator.w3.org/

error: The element button must not appear as a descendant of the a element.

Why not simply apply a (CSS) class to your link and make it appear as a button.

erb:

<%= link_to "Button Text", new_post_path, class: 'button' %>

produces (valid & semantic) HTML:

<a class="button" href="/post/new">Button Text</a>

which you can then style to look like a button.

Example: http://jsfiddle.net/nelsonic/FQK9M/7/

like image 104
nelsonic Avatar answered Oct 22 '22 20:10

nelsonic


Just to throw another option out there since I had a scenario where the button_to option didn't work. This looks kind of similar to that.

<%= link_to '<button type="button">New Post</button>'.html_safe, new_post_path %>

What I basically wanted is a button that doesn't turn into a submit, since I have multiple buttons on the page that aren't related to a form, and I really just want it to just go to another page.

like image 14
Ryan Shih Avatar answered Oct 22 '22 21:10

Ryan Shih