How to use a specific controller\action on "onchange" for Select_tag in ruby on rails - ruby-on-rails

Im knew on MVC and on Ruby on rail environment
I have this code
<%= select :language, :language_id,
options_for_select([ "Arabic", "English"]),
{:prompt => "#{t('language')}"},
{:onChange => "#{remote_function(:url => {:controller => 'ConfigurationController',:action => "change_language"}
)}"} %>
And I cant make the Select to call this action and make PostBack for the page on on change
after selected index change nothing is happening ?

Since this is a remote function call. can you see in browser's console if there are any errors returned from server.
the syntax of select_tag, you are using looks fine.
Edit:
did u try alerting some thing onchange event? refer this syntax
<%= select_tag "language", options_from_collection_for_select(#collection,'value','name'), html_options = { :onChange=> "alert('');" :style=> "display:block;" } %>
where u can create your collection using,
#collection = ["en","ab"]
#collection = #collection.map { |name, value| OpenStruct.new(:value => name, :name => name) }

What version of Rails are you using? It looks like remote_function was depracated in 3.1 http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_function
Use jQuery to respond to the change event:
jQuery ->
$("#select_id").change ->
$.ajax(
url: "url",
dataType: "json",
data: "data to send")
.done (data) ->
do_something_on_success()
.fail (data) ->
do_something_on_fail()

Related

Ruby on Rails (Rails 2.3.2) f.select onchange() event is not triggered in jQuery

I have creating a select option on using the f.select form helper as follow
<%= f.select(:sales_type, {'Direct' => 'Direct', 'ME' => 'ME', 'Direct Staff' => 'Direct Staff'},{:onchange => "hello();"}) %>
and my JavaScript function is as follow
$(function () {
function helllo(){
alert("from hello");
}
});
while I trigger the f.select I expect the alert box should be shown. But the trigger is not triggered while I choose different options
Let me know which part I did wrong ?
Thanks in advance.
<%= f.select(:sales_type, {'Direct' => 'Direct', 'ME' => 'ME', 'Direct Staff' => 'Direct Staff'},{},{:onchange => "hello();"}) %>
will work i guess. correct syntax for select is
select(method, choices = nil, options = {}, html_options = {}, &block)

url_for and remote: true

I've got an issue with Rails. I want a select form which render a partial view when clicked. I want the partial views to be effective without refreshing the whole document (Ajax) but it seems that remote: true does not work for me...
What I have currently and refresh the whole document:
= form_tag url_for(action: :index), method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
What I've tried :
= form_tag url_for(action: :index), remote: true, method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
How do I apply the remote: true option with url_for? If not possible, I could use some help finding a workaround.
As per the docs you can specify the remote option to the form_tag method, like so:
form_tag(url_for(controller: :charmander, action: :ember), remote: true, method: :get, class: 'pokemon-form') do
# form logic
end
However, this will only trigger the ajax:success event when the whole form is submitted.
From your question it seems to me that you want to re-render some partial when your select value changes. I'm not sure how you use the submit_on_change data attribute, but if I'm correct in assuming that you make it submit the entire form when the select vaule changes then all you need to do is listen for the ajax:success event for the entire form, like so:
$('.pokemon-form').on('ajax:success', function (event, data, status, xhr) {
// Do something with data, which would be the rendered partial returned
// from the server call.
});
Ended up using an onclick and a JavaScript function. Though it may not be the best solution nor the prettier, it works like a charm for me.
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", onclick: 'ajaxSelectedShop('+String(8)+')'

call a controller and method on select change with rails

i want to call a AJAX query on select change.
I found this code fragment, but it doesnt work on rails 4, or im doing it wrong
<%= f.select(:resource_id, Resource.all.collect {|resource| [ resource.name, resource.id ] }, :class => "medium", :onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})) %>
and im geting this error
undefined method `remote_function' for #<#<Class:0x007f3daff24a88>:0x007f3d9c670210>
any ideas what im doing wrong ?
This should give you a hint:
<%= f.select(:resource_id, Resource.all.collect {|resource| [ resource.name, resource.id ] }, :class => "medium" %>
#javascript code to make an Ajax call:
$('select#your_model_name_resource_id').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax('/relative/path/to/your/action', data: { id: selected_resource_id })
})
When a user change the value of the select, it should perform an Ajax request to your server at this location: /relative/path/to/your/action?id=12 (if id selected was twelve)
The remote_function has been deprecated and removed from rails. You need to write some javascript now (very simple though).
Unless you are willing to install prototype-rails gem, which will add this helper back to your rails.

Calling a function in application.js after an AJAX request

Spinning my wheels trying to figure this out. I have a link that when clicked retrieves a form from the server. The form has 3 buttons and 1 text input. I'm trying to get the non-submit buttons to respond to JS which they don't do after the form is returned from the server.
I've create a function in lists.js which the ajax:success is trying to call, but I'm not doing something right. I've tested the function in lists.js and I know it works, I'm just not calling it right.
Here are the relevant files. How do I activate the showPicturePicker function so it can be used after the AJAX response is inserted?
Lists.js
$("#new_list")
.bind "ajax:success", (evt, xhr, settings) ->
$("#list-item").html(xhr)
showPicturePicker
showPicturePicker = () ->
$('#picture').click (e) ->
e.preventDefault()
alert "yeah, you figured it out"
$(document).ready showPicturePicker
_new.html.haml (the form returned from the server)
= form_for [#list, #item], :remote => true, :html => {:class => 'form-inline'} do |f|
.input-append
= f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
%button#picture.btn
%span.icon-camera
%button#link.btn{:style => "font-size: 10px;"}
http://
.secondary-fields{:style => "display: none"}
.field.margin
= f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
.field.margin
= f.file_field "picture"
= f.hidden_field "picture_cache"
.clearfix
= link_to "blah", "#{}", :class => "fuck-me"
= f.submit "Add Item", :class => 'btn', :id => "add-item"
This is a problem i'll need to solve in other places as well and I appreciate the help.
application.js is wrapped with an IIFE (immediately invoked function expression) and variables defined there will not be visible in other files unless you explicitly make them available to the global scope (either by attaching them to window or some other object).
In application.js, try:
#showPicturePicker = ->
...
# or window.showPicturePicker = ->
"Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident."
http://coffeescript.org/#lexical_scope

RoR select_tag selected value

I'am using select_tag and I want to pass selected value in href :onchange
I couldnt fetch the selected value
Please guide me how to fetch the selected value and pass in href
I'am using following code
<%= select_tag "name",
options_for_select(#user.names.map {|c| [c.firstname,c.id]}),
:onchange =>"document.location.href='/names/value'" %>
In the code in href='/names/**value** at the place of value I have to pass selected value
Thanks
I'm not sure to understand your question but you can try this:
<%= select_tag "name", options_for_select(#user.names.map {|c| [c.firstname,c.id]}),:onchange =>"document.location.href='/names/'+this.value" %>
Thereby, the selected value is used during the onchange event.
Try this
<%= select_tag "name",
options_for_select(#user.names.map {|c| [c.firstname,c.id]}),
:onchange => "document.location.href=/names/ + $(this).value" %>
I think the suggested methods j and kiva would not work because the javascript components are rendered (written to the static html file) at the initial stage, rails is server side, and what is suggested in their posts is more client side.
I achieved it like this ->
add a onchange => myJavaScriptFunction()
and then code the url change in the javascript function()
using pure javascript, no rails involvement.
here's my snippet -
<%= select_tag :clientid, options_for_select(#options),
:include_blank => false,
:onchange => "myfunction(this)"
%>
function myfunction(combo_box)
{
//var combo1 = document.getElementById('clientid');
var value1 = combo_box.options[combo_box.selectedIndex].text;
var value2 = combo_box.selectedIndex;
document.getElementById('session_dump').innerHTML='<hr>'+value2 + '::::=> ' + value1+'<hr>';
}
Hope its useful...

Resources