Is Rails Collection_Select onchange still supported? - javascript

I'm trying to create a text field that is visible only when the user selects "Other" from a dropdown menu.
I've done this before with some jQuery and rails "select" but I haven't been able to get it working for "collection_select".
People say that onChange should work but so far I have had no luck.
Collection Select:
<%= f.collection_select(:professor, Professor.order(:fullname), :id, :fullname,
include_blank: false, :prompt => "Other", :onchange => "review_professor();")%>
<%= f.text_field :professor, class: "class-reveal", style: "display: none;"%>
Javascript:
review_professor = function() {
if(this.value == "Other") {
$('.class-reveal').show();
$('.class-reveal').val('');
}else{
$('.class-reaveal').hide();
$('.class-reveal').val(this.value);
}
});
Any ideas of why this is not working or another way I can do this? Is collection_select still supported?

It still works for collection_select, it just needs to go in the html_options hash, like so:
{include_blank: false, prompt: "Other"}, {onchange: "review_professor();"}

Related

Add a new form based on another form's data?

I have a dropdown menu that allows the user to select a time period (ie: January 2018, 1st Trimester, Summer 2018, etc.). At the very bottom there's an option labelled "Other". How can I make it so that if the user selects "Other", and text-input form appears beneath that so that they can elaborate on what "Other" means? Here's my current code:
HTML:
Time Period:
<% if f.object.award.add_period? %>
<div class="time_period_<%= f.object.award.id %>" id="otherBoolID">
<%= f.select :time_period, Award::TimePeriods, {:include_blank => true}, { :class => "date_dropdown"} %>
</div>
<% end %>
<div id="boolID" <%= "hidden" %>>
<%= f.input :time_period, :label => false, placeholder: "Other (please specify)", :input_html => { :class => 'awardform' } %>
</div>
JavaScript/JQuery:
$('#otherBoolID').change(function () {
var x = document.getElementById('otherBoolID').value;
if (x == "Other") {
document.getElementById('boolID').style.display = 'visible';
}
});
Any idea what's going wrong? Currently the "other" form is hidden on page load, but doesn't become visible if you select "Other" in the dropdown menu. If it's worth mentioning, I'm working with a ruby on rails framework.
Could the issue be that the id="otherBoolID" is on the <div> rather than <select> tag?

How do you add onchange action to collection_select?

I have the following select drop down in my rails. I'm following the syntax from the API( http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select):
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
<%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"} ) %>
function updateTextArea(){
alert('source changed')
}
I'm able to get the drop down to display just fine with the values from the DB when I don't include html_options. However, I'm stuck trying to get an onchange action to occur.
I think options needs to be in a hash (the part you have include_blank in currently). Try changing this
<%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"} ) %>
to this
<%= collection_select(:sources, :source_id, Source.all, :id, :name, options = {include_blank: "Please select a source..."}, html_options = {:onchange => "updateTextArea()"} ) %>
I believe that in place of options = or html_options = you need to pass actual hash itself (like you actually did with include_blank => true). I would only explicitly mark those hashes with curly braces to separate them:
<%= collection_select(:sources, :source_id, Source.all, :id, :name, { :include_blank => "Please select a source..."}, {:onchange => "updateTextArea()"} ) %>
Hope this helps.
EDIT:
I forgot to add that if updateTextArea() JS function is not bind to a window there might be a problem with picking it up (I had similar problems in the past). For safety I would also do (if you are not using CoffeScript):
window.updateTextArea = function() { /* Your code */ }

show and hide blocks while changing in dropdown [Rails4, jquery]

I have a form which contains a dropdown of 3 values QUESTIONS_TYPES = {'single', 'multiple', A text}
<div class="field">
<%= f.label :question_type %><br>
<%= f.select :question_type, Question::QUESTIONS_TYPES, prompt: 'Select a question type' %>
</div>
Using Jquery, this dropdown shows other fields(in the block whose class is .answers_list) depending of the choosing value.
$(document).ready(function(){
$('#question_question_type').change(function(){
var qst_type = $('#question_question_type option:selected').text()
if (qst_type == 'Multiple' || qst_type == 'Single'){
$('.answers_list').show();
} else{
$('.answers_list').hide();
}
});
});
The thing is when I access to the form via a link:
<%= link_to 'New Question', new_question_path %>
My dropdown doesn't respond the jQuery action, once i refresh the page it does. Any suggestion?
Thanks!!
use
$( ".target" ).toggle();
see
Click here

How to make Drop Down List, if model is created based on Single Table Inheritance on Ruby on Rails 4

I want to have form which shown fields based on the Type of Publications you select. I have used Single Table Inheritance (according to this [link] http://blog.thirst.co/post/14885390861/rails-single-table-inheritance) to create Publication model (base model), and subclasses (book_chapter, book_whole, conference_article, journal_article). Fields of Publications model are as follows: type, author, title, year, publication, volume, issue, page, keywords, abstract, publisher, placeofpublication, editor, seriestitle, seriesvolume, seriesissue, issn, isbn, area, url, doi.
So, based on the Type that will be chosen (for instance book_chapter), I want to have particular fields of Publications.
I handled to create dropdown list with types, but when select the type and create publications the Type record do not saved on database. This is the code for type dropdown
list
<%= f.label :type, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :type, Publication.order(:type), :id, :type, include_blank: true, :class => 'text_field' %>
</div>
</div>
Are you sure type is permited as an accessible param in your controller
def publication_params
params.require(:publication).permit(:type)
end
Are you sure the values for your options in the select are the right ones ?
Why is your collection_select containing :id
<%= f.collection_select :type, Publication.order(:type), :id, :type, include_blank: true, :class => 'text_field' %>
instead of :type
<%= f.collection_select :type, Publication.order(:type), :type, :type, include_blank: true, :class => 'text_field' %>
Regarding your second question, the answer will rely on a javascript / client side implementation.
Using jQuery you would implement something like this
# JS ($=jQuery)
# assuming your type select has id='type_select'
# assuming your fields inside your form have class 'field'
$('#type_select').change(function(event){
current_type = $(e.target).val();
$(e.target).parents('form').children('.field').each(function(el,i){
if($.inArray($(el).attr('id'), form_fields_for(current_type)){
$(el).show();
}else{
$(el).hide();
}
});
});
var form_fields_for= function(type){
{ book_chapter: [field1_id, field2_id, field3_id, field4_id],
book_whole: [field1_id, field2_id],
conference_article: [field1_id],
journal_article: [field1_id, field2_id, field3_id, field4_id, field5_id]
}[type];
};
Another solution would be to set specific classes for each fields for each of your types:
If we take the same assumptions as above, you would have rails to show a form like this:
# pseudocode (html form)
form
field1 class='book_chapter book_whole conference_article journal_article'
field2 class='book_chapter book_whole journal_article'
field3 class='book_chapter journal_article'
...
And then you would hide or show these specific classes
# JS ($=jQuery)
$('#type_select').change(function(event){
current_type = $(e.target).val();
$('.' + current_type).show();
$(e.target).parents('form').children('.field').each(function(el,i){
if(!$(el).hasClass(current_type)){
$(el).hide();
}
});
});

How reset multiple scroll down selected menus

I've 2 scroll down menus like
<%= f.label :term_id, "TERM *"%>
<br>
<%= f.collection_select :term_id, Term.order(:id), :id, :name, include_blank: true %>
<br>
<%= f.label :lesson_id, "LESSON *" %>
<br>
<%= f.grouped_collection_select :lesson_id, Term.order(:name), :lessons, :name, :id, :name, include_blank: "Ders Seçiniz" %>
and the javascript code is like that
jQuery ->
lessons = $('#demand_lesson_id').html()
$('#demand_term_id').change ->
term = $('#demand_term_id :selected').text()
options = $(lessons).filter("optgroup[label='#{term}']").html()
if options
$('#demand_lesson_id').html(options)
else
$('#demand_lesson_id').empty()
I need to reset when I click to reset button. but all forms elements are cleaned except lessons group collection.
How can I manage it?
The form reset button should restore all your select's default options. But if you need something to override whatever it is overriding the reset button behaviour, here's some plain old jQuery (Sorry, but I'm not familiar with CoffeeScript).
See it at the following jsFiddle
$(function(){
// reset button click
$('#myReset').click(function(){
// cycle through each option and restore to default
$('#myForm select option').each(function(){
$(this).prop('selected', $(this).prop('defaultSelected'));
});
});
});

Categories

Resources