rails selectbox_tag onchange() - ruby-on-rails

Say we have a select box:
/app/views/tape/_form.html.erb
<%= f.select :tape, Tape::LIST_TAPES %>
and a .js.coffee file that i would like to trigger when some value is selected in selectbox:
/app/assets/javascripts/tapes.js.coffee
function selectBoxValue(value){
# value -- selected in selectbox;
console.log("box_value = ", value);
}
How can it be done in RoR 3.2?
Here's what i mean within html+js.
P.S.
I'm new to Rails. Sorry for my English and thank you.

Something like that:
<%= f.select :tape, Tape::LIST_TAPES, :id => 'some_id' %>
js file:
$(function(){
$('#some_id').change(function(){
selectBoxValue(this.value);
});
});
Pay attention that your select tag already has id so you can use it and remove :id => 'some_id'

Related

How to add custom menu opton in Tinymce in Rails

I am using tinymce-rails gem for Tinymce and I want to add custom menu option. Right now I am doing what is suggested in the readme of gem like:
<%= f.input :content , :label => false , :placeholder => 'Content', input_html: {class: "tinymce"} %>
<%= tinymce %>
I am using simple-form.
I want to add a drop-down in the editor with a bunch of options (I have an array of names) and when user clicks on an option then the selected name should be inserted in the view of editor. And those names will be dynamic.
I tried to pass many options to the initialiser tinymce but unable to get the result.
Rather than using the default initiator from the gem you could initiate tinymce manually and create the menu item at the same time:
http://www.tinymce.com/tryit/menuitem.php
Something like this:
<script type="text/javascript">
tinymce.init({
selector: '.my-class textarea',
toolbar: "styleselect | bold italic | mybutton",
setup: function(editor) {
<% #my_items.each_with_index do |name, index| %>
editor.addMenuItem('<%= name %>', {
text: '<%= name %>',
context: 'tools',
onclick: function() {
editor.insertContent('<%= name %>');
}
<%= index == (#my_items.count - 1) ? '});' : '}),' %>
< % end %>
});
</script>
We use a ternary operator to choose the correct closing tag based on the index of the names.
Theoretically you can also do this in the config/tinymce.yml file, but due to the dynamic nature it's not really plausible.
Something else you may want to look into is passing the menu to the activeEditor like:
tinyMCE.activeEditor.controlManager.get('my_menu')

Bootstrap Typeahead in Rails

I'm using Bootstrap-sass and formtastic in my Rails application, and I'm not sure why the bootstrap-typeahead feature isn't working.
Form partial:
<%= f.input :tag, :input_html => { :'data-provide' => "typeahead", :'data-source' => '["hello", "hellow", "heaven", "helo", "herr"]' } %>
application.js manifest:
//= require bootstrap-typeahead //typeahead is correctly loaded, checked with firebug
result HTML source code:
<input :data-minLength="2" data-provide="typeahead" data-source="["hello", "hellow", "heaven", "helo", "herr"]"
In the end, I will need to customize typeahead to get the performance I want, but even this simple javascript isn't working for some reason. I cant find anything wrong with the code. Could anyone help me?
UPDATE:
I tried it in the javascript way as follows:
<script> //call typeahead
$(function() {
$('input#type_ahead').typeahead({
'source' : ["hello", "heaven", "heythere"]
});
})
</script>
<%= f.input :tag_list, :input_html => { :id => "type_ahead" }, %> //input tag
And still it seems like typeahead fails to work. i.e) typing in "he" does not get me a dropdown of those three items in the above array. Does anyone have an idea?
I think you need to set html_safe for:
{ :'data-source' => '["hello", "hellow", "heaven", "helo", "herr"]'.html_safe }
Have you called the typeahead() method when your page loads? You need to do something like this;
$(function() {
$('input').typeahead();
})
You'll need to assign a class or id to your input to bind the typeahead to it specifically (Rails probably has assigned an id to it automatically, I'm presuming you've omitted it specifically)
$(function() {
$('input#my-tag-field-with-a-cool-typeahead').typeahead();
})
edit:
The following worked for me. It'll take a bit of modification to the rails part to fit your situation, but this definitely works.
<script>
$(function() {
$('input#type_ahead').typeahead()
}
</script>
<%= text_field_tag :test_type, '', data: {provide: 'typeahead', source: "['hello','heythere','heaven']"} %>

Array as Parameter from Rails Select Helper

I'm working on a legacy project that is using acts_as_taggable_on which expects tags to come in arrays. I have a select box allowing users to select a tag on a Course in a field called categories. The only way mass assignment create will work is if params looks like this params = {:course => {:categories => ['Presentation']}}. I've currently a view with this helper:
<%= f.select 'categories', ['Presentation' , 'Round Table' , 'Demo', 'Hands-on'] %>
Which will give me a parameter like params = {:course => {:categories => 'Presentation'}}. This doesn't work since Acts as tag gable apparently can't handle being passed anything other than a collection.
I've tried changing categories to categories[] but then I get this error:
undefined method `categories[]' for #<Course:0x007f9d95c5b810>
Does anyone know the correct way to format my select tag to return an array to the controller? I'm using Rails 3.2.3
I didn't work with acts_as_taggable_on, but maybe this simple hack will be suitable for you? You should put it before mass-assignment.
category = params[:course][:categories]
params[:course][:categories] = [category]
If you are only going to allow the selection of ONE tag, you could do:
<%= f.select 'categories', [['Presentation'] , ['Round Table'] , ['Demo'], ['Hands-on']] %>
Each one item array will have first for the display value, and last for the return value, which in this case will both return the same thing, as the first element of the array is the same as the last element when the array as one element.
Seems like select doesn't give you that option.
If I understand correctly, one option might be to use a select_tag instead and just be explicit about where you want the selection in the params:
<%= select_tag 'course[categories][]', options_for_select(['Presentation' , 'Round Table' , 'Demo', 'Hands-on']) %>
That ought to get your params the way you need them.
Here's what I'm using for one of my projects:
<% options = { include_blank: true } %>
<% html_options = { required: true, name: "#{f.object_name}[#{resource.id}][days][]" } %>
<%= f.select :days, DAYS, options, html_options %>
Without html_options[:name], Rails handles the name of the select tag and spits out something like
service[service_add_ons_attributes][11][days]
but I need
service[service_add_ons_attributes][11][days][]
So I override it.
Hope that helps.

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...

How to add an onchange event to select tag in rails

How do I add an onchange event here?
Framework: rails
Database: MySQL
I am populating the options from the database and that made me use options_from_collection_for_select
select_tag(:variable,options_from_collection_for_select(:all, :id, :name))
select_tag takes an options hash as its final parameter, in which you can add any HTML attributes for the select. So to add an onchange attribute:
select_tag :variable, options_from_collection_for_select(:all, :id, :name), onchange: 'yourOnChangeHandler()'
try something like:
:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})
For a select_tag, just add:
{:onchange => "myHandler();" }
Also, if onchange doesn't work you might want to try onChange with a capital C.
Finally, make sure NOT TO CONFUSE a select_tag with a form select.
See my answer to a similar question, only regarding a form select and not a select_tag
Adding An Onchange Event To A Form Select
You may want to add an onchange attribute inline:
select_tag(:variable,options_from_collection_for_select(:all, :id, :name)), {:onchange => "(function(e){ e.target.value }).apply(this,arguments)"}
For my case, I'm not sure where to put the named functions, or sometimes I find it tedious to create a function just to create a simple tag. So people tend to write an inline function.
but a simple line like {onchange: "e.target.value"} won't work, because there are no variables (e.g. event) defined.
Solution would be a self executing function that accepts arguments

Resources