link_to method and click event in Rails - ruby-on-rails

How do I create a link of this type:
<a href="#" onclick="document.getElementById('search').value=this.value">
using method link_to in Rails?
I couldn't figure it out from Rails docs.

You can use link_to_function (removed in Rails 4.1):
link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'
Or, if you absolutely need to use link_to:
link_to 'Another link with obtrusive JavaScript', '#',
:onclick => 'alert("Please no!")'
However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.
Instead, your Rails code should simply be something like this:
link_to 'Link with unobtrusive JavaScript',
'/actual/url/in/case/javascript/is/broken',
:id => 'my-link'
And assuming you're using the Prototype JS framework, JS like this in your application.js:
$('my-link').observe('click', function (event) {
alert('Hooray!');
event.stop(); // Prevent link from following through to its given href
});
Or if you're using jQuery:
$('#my-link').click(function (event) {
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});

just use
=link_to "link", "javascript:function()"

another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});

Related

Ruby on Rails & FullCalendar: Is there any way to add a link to the title header?

I have a page in my simple application that displays a calendar with the jQuery plugin http://fullcalendar.io/.
I want to add a link to the title such that the user gets navigated somewhere else to a different view. Is this possible? The calendar itself has poor documentation. Specifically I want to add a FontAwesome icon and have it redirect the user on click.
I know that customizing the title is pretty easy – just specify the custom title like this:
<div id="calendar"></div>
<script>
$('#calendar').fullCalendar({
header: {
left: 'prevYear,nextYear',
center: 'title',
},
titleFormat: '[Hello, World!]'
});
</script>
However, I am trying to add a link next to the calendar using a Rails helper link_to. Is this possible? Here is my attempt, but it does not work:
<div id="calendar"></div>
<script>
$('#calendar').fullCalendar({
header: {
left: 'prevYear,nextYear',
center: 'title',
},
titleFormat: '[<%= link_to '<i class="fa fa-icon"></i>'.html_safe, some_path %>']'
});
</script>
You have a typo on this line:
titleFormat: '[<%= link_to '<i class="fa fa-icon"></i>'.html_safe, some_path %>']'
There is an extra single quote after the %>. Try this:
titleFormat: '[<%= link_to '<i class="fa fa-icon"></i>'.html_safe, some_path %>]'
If you still have a problem after fixing that, try looking into what FullCalendar’s titleFormat property supports. I don’t know if FullCalendar tries to allow you to put arbitrary HTML into that property – that property’s docs don’t make it clear. You could check by looking in the rest of FullCalendar’s documentation or its source code that handles that property.
Your use of link_to and html_safe looks good to me.

How do I hide a button after a current user clicks on a button in ruby

I am trying to hide this button in ruby once it is clicked so it doesn't show up again and the user thinks their request has not went through. I just want this clickable once then removed from page not just disabled
<% if #ride_request clicks %>
<%= link_to "Book Ride", :controller => "/request", :action => "book", :id => #ride.id %>
Consider using disable_with, which IIRC works with both link_to and submit buttons:
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
You can this javascript (jQuery) inside your controller specific .js file
$(document).ready(function() {
$('#replace_id').click(function (){
$(this).hide();
});
});
All you need to do now is add the id of the object and substitute it with replace_id.
you could try jQuery's element.hide() http://api.jquery.com/hide/#hide
or you could toggle css' display:none for that button
or you could try jQuery's element.remove() http://www.w3schools.com/jquery/html_remove.asp
Your question is actually about JS, rather than Rails.
You have to remember Rails is a server-side framework, which means it takes a request from the front-end, and then processes a response for you. This means that any UX stuff on the front-end needs to be handled with JS
To do that, you'd be best using the $("element").remove(); function of Javascript:
DEMO
$(document).on("click", "element", function(){
$(this).fadeOut(150, function() {
$(this).remove();
});
});
This will fade the button out, and then remove it from the DOM

How to make select options in Rails that point to URLs?

I am trying to build a select menu whose options simply point to URLs:
# Ruby:
form_tag "", :method => 'get' do
select_tag "", options_for_select([["Memberships", memberships_url], ["Transactions", transactions_url]])
end
# jQuery:
$('form').on('change', function() {
$(this).submit();
});
However, this isn't working. What am I missing?
All you are doing is submitting the form which does not process as a redirection you would need an additional hook for the form onsubmit event to process the redirection but based on your concept this seems unnecessary .
How does this work:
$('form select').on('change', function() {
window.location.href = $(this).val();
});
Or all in jQuery I believe you can use
$('form select').on('change', function() {
$(location).attr('href',this.val());
});
Obviously this hook will apply to all form select DOM objects so I would suggest adding an id to the select like so (notice I dropped the form tag as it is not needed for functionality)
select_tag "navigation", options_for_select([["Memberships", memberships_url], ["Transactions", transactions_url]])
$('#navigation').on('change', function() {
window.location.href = $(this).val();
});
You could also simulate a redirect instead of a link click using
window.location.replace($(this).val());

How to add an onchange listener for form elements in Ruby on Rails?

I am writing a form in Ruby on Rails and want to have a select box that calls a Javascript function. In the form file, this is the line I am using to try to add the select box:
<%= f.select :question_select, Question.all, :prompt => "New Question", :onchange => "displayQuestion(this)" %>
In my application.js file, I just have:
function displayQuestion(link) {
alert("Changed question");
}
I am going to be dynamically adding these form elements to a page, so I can't just use jQuery in the application.js file to add a function to a specific form element. Can anyone tell me what I'm doing wrong?
As you may know, Rails 3 strongly encourages UJS (unobtrusive JavaScript), which basically means that the JavaScript does the heavy lifting, and that you shouldn't tie your client-side interactivity in with your form generators. I would recommend doing something very similar here--just because you're adding elements dynamically doesn't mean you can't use jQuery to watch for changes on them.
In your template:
<%= f.select :question_select, Question.all, {prompt: "New Question"}, data: { question: true } %>
This creates something like the following:
<select id="..." data-question="true">
...
</select>
Then, in JavaScript, you can use event delegation to watch for change events on any element with data-question set on the entire document:
$(function() {
$(document).on('change', '[data-question]', function() {
// this == the element that fired the change event
alert('Changed question');
});
});
Note: Instead of using data-question, you could simply add a class to the element, and then modify your jQuery to use that class:
$(function() {
$(document).on('change', '.question', function() {
// this == the element that fired the change event
alert('Changed question');
});
});
I generally try to minimize the use of CSS selectors in my JavaScript so that designers are free to change them to whatever they want without breaking things, but it works just as well.
select_tag :variable, options_from_collection_for_select(:all, :id, :name), :onchange => 'your_onchange_handler()'

how to close view template in Rails 3

I have opened the view template as popup by using the following code:
<%= link_to 'New User', "/users/new", :method => :get, :target => "_blank" %>
controller code:
def new
render :layout => false
end
the new.html.erb is having few textboxes and buttons as Save and Cancel
My problem is how can i close the popup upon clicking Save or Cancel button?
Thank u,
Sudhir C.N.
This a more a javascript question rather than one specific to Rails.
Your Cancel button is easy enough, something like:
<html>
<script>
function CloseWindow() {
ww = window.open(window.location, "_self");
ww.close();
}
</script>
<button type="button" onclick="CloseWindow();">Cancel</button>
</html>
(stolen from http://snippets.dzone.com/posts/show/267)
Your submit button shouldn't change. It will need to POST to your controller as normal. The successful response rendered by the controller should display a "Success" message in the flash and could then close the window automatically after, say, three seconds:
<script>
setTimeout( function() { CloseWindow(); }, 3000);
</script>
This is a pretty simple solution. Maybe consider investigating some popup libraries for either prototype or jquery (depending on the library you're using). Not sure whether modern popup blockers render these D.O.A. though. Your target="_blank" approach should play nice with popup blockers.
Edit: if you're using jquery maybe consider something like the modal dialog: http://jqueryui.com/demos/dialog/#modal-form
You will need to do it with javascript. After the user saves you can respond with another view that sends this:
<script type="text/javascript">
window.close();
</script>

Resources