Venus
Venus

Reputation: 123

How to open a new tab on button click in Rails?

I have a button which navigate user to another page. (It has to be button not link). I want to open the page in new tab (or even new window!). Do I have to use JavaScript? or is there any other way! I'll appreciate your help.

Cheers.

Upvotes: 11

Views: 9586

Answers (5)

Tom Harrison
Tom Harrison

Reputation: 14018

To expand on the answers suggesting using `target="_blank" in Rails...

If you're using the button_to helper, this is automatically wrapped in a form by Rails. It's the form tag that needs this attribute. To get it, pass it as a value in the hash of html options, for example:

button_to t(:translated_text), foo_path(foo.id), class: 'btn btn-primary', form: {target: '_blank'}

the class: and form: are elements of the html_options hash. The form: option is special because it tell Rails you want to pass the HTML option to the form tag, instead of the input tag of the button itself.

Upvotes: 21

index
index

Reputation: 3727

With javascript, this selects all your buttons that have href attribute

$("button[href]").click(function() {
   window.open($(this).attr('href'));
});

This actually opens a new window but I think when the browser forces it to open in new tab, it will open in a new tab.

Cheers!

Upvotes: 0

Andrew Nesbitt
Andrew Nesbitt

Reputation: 6046

target="_blank" is what you want, but it only works on forms and links.

You can style a link to look like a button with css quite easily, which would be the cleanest way to achieve what you are after.

Unless your button is within a form, then you can just add target="_blank" to your form and it should work.

Upvotes: 0

vivek salve
vivek salve

Reputation: 991

$('#btn').click(function(){
   window.open('pageName');

})

Upvotes: 0

bento
bento

Reputation: 2099

This is rather an html question. If you want to use buttons instead of links, you can provide the target attribute to the form as described here: http://www.w3schools.com/tags/att_form_target.asp

Upvotes: 0

Related Questions