Show different controls depending on rails collection select (selected) item - javascript

Sorry i couldn't get a better title to my question but hope my explanation will give you guys a better idea of what's going on?
I have a model Airport and three other models West East and South that aren't related in anyway only that Airport model needs some of the other fields like this form shows.
<%= form_for(#airport) do %>
<%= f.collection_select(:airport_name, AirPortManager.all, etc...) %>
//AirPortManager is a collection of available airports
<div class="west-airports" style="display:none;">
<%= f.collection_select(:airline_name, WestAirlineManager.all, ....) %>
</div>
<div class="east-airports" style="display: none;">
<%= f.collection_select(:airline_name, EastAirlineManager.all, ....) %>
</div>
<div class="south-airports" style="display: none;">
<%= f.collection_select(:airline_name, EastAirlineManager.all, ....) %>
</div>
<% end %>
The airport model validates :airline_name, :presence => true . Now the problem is with
my javascript. If a user selects airport west in AirPortManager.all the west-airports div` should be shown and so on. But my validation method airport keeps throwing a required field error for :airline_name and if not that it keeps a value from a previous selection. How can i pass the visible div value to airport parameters or if i select an empty value the previous value shoudn't remain constant. Below is my javascript and hope my question makes sense.
<script type="text/javascript">
$(document).ready(function() {
$("#aiport_manager_aiport_name").change(function(){
var value = this.value;
if (value == "West") {
$('.west-aiports').show();
$('.east-airports').attr("disabled", true);
$('.east-airports').hide();
$('.south-airports').attr("disabled", true);
$('.south-airports').hide();
}
else if (value == "East") {
$('.east-airports').show();
$('.west-aports').hide();
$('.west-airports').attr("disabled", true);
$('.south-airports').hide();
$('.south-airports').attr("disabled", true);
}
else if (value == "South") {
$('.south-aiports').show();
$('.west-airports').hide();
$('.west-airports').attr("disabled", true);
$('.east-airports').hide();
$('.east-airports').attr("disabled", true);
}
});
});
</script>
I try and disable the other collection_selects in their respective divs but still get a validation error or get a persistent value.

Your form has multiple elements with the same name (:airline_name), which is the core problem. You're on the right track with disabling, but you're disabling the div instead of the select. I would just do this:
// before form is submitted, disable all hidden selects
$('form').on('submit', function(e) {
$('select:hidden').prop('disabled', true);
});

Related

Javascript/JQuery error message didn't hide in Safari

In my registration form I have some validation logic which works perfectly fine in Chrome but in Safari error message don't disappear below form after filling empty fields. It looks like show() and hide() doesn't work and I don't now why because based on this https://www.quirksmode.org/dom/events/index.html it should worked.
if (registrationsForm.length > 0) {
var emailField = $('#users-registrations-email');
var emailConfirmationField = $('#users-registrations-email-confirmation');
var emailInvalidMsg = $('.bank-employees-users-registration__registrations__not-identical-email');
var obligatoryInvalidMsg = $('.bank-employees-users-registration__registrations__email--invalid');
submit.on('click', function(e) {
e.preventDefault();
if (emailField.val() !== emailConfirmationField.val() && emailField.length > 0) {
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
emailConfirmationField[0].setCustomValidity('Incorrect confirmation email');
if (emailField.val() !== '') obligatoryInvalidMsg.hide();
} else {
emailConfirmationField[0].setCustomValidity('');
}
validateEmail();
var invalidInput = $('input:invalid');
if (invalidInput.length === 0 && !fileInput.hasClass('invalid')) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
}
});
}
Function which is responsible for input validation:
function validateInput() {
$('input').change(function() {
if ($(this).is(':valid')) {
$(this).removeClass('invalid');
}
});
}
Edit
This is a code snippet from view
new.html.erb
<div class="floating-label bank-employees-users-registration__registrations-input--wrapper">
<%= f.email_field :email, class: "bank-employees-users-registration__registrations-input floating-field", id: "users-registrations-email", placeholder: t('.email'), required: true, aria_required: true %>
<%= f.label :email, t('.email'), class: "floating-label-placeholder" %>
<span class="bank-employees-users-registration__registrations__not-identical-email">
<%= t('.email_not_identical') %>
</span>
<span
class="bank-employees-users-registration__registrations-input--invalid-msg bank-employees-users-registration__registrations__email--invalid"
id="bank-employees-users-registration__registrations__email--invalid">
<%= t'.obligatory' %></span>
<% if #registration_form.errors.full_messages_for(:email).first %>
<div class="alert alert-danger">
<div class="error-explanation">
<%= t('activerecord.errors.models.user.attributes.email.taken') %>
</div>
</div>
<% end %>
</div>
Edit2
Maybe this will be helpful - as you see there are some email validations where two email address has to be equal. When I provide different email address it shows me error message that they are not equal but if I correct them, the error will be changed to - this field is required. I was trying to implement this solution jquery .show() and .hide() not working in safari - adding spinner to <a href but without any positive results.
Why not get rid of all that and use HTML5 fields? They have client-side validations that work across browsers and you can validate input on the server side using model validations, let Rails deal with all that.
I know it may be a bit of upfront investment into refactoring all that but otherwise things will only get worse in the long term if you keep doing what you're doing.
Also look at the Bootstrap form gem in case you're using Bootstrap.

Remove form input based on value in simple form collection

In my rails app I have a lesson model that belongs to a course. In the lesson new page, there is a collection of courses that can be selected for the lesson. Courses have several 'course_types' but the most important one for this question is the 'physical' course_type. This is the sample code
<%= f.association :course, collection: current_academy.courses.collect
{ |u| [u.title, u.id] }, prompt: t("select") %>
On the same page, you can add a video link to the lesson
<%= f.input :video, label: t(".vimeo_link_to_video") %>
I want to be able to remove the video link if the course_type is 'physical'.
In my js, I have
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="lesson[course_id]"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
if(event.target.value == "97" ) {
$(".vimeo").hide();
}
else {
$(".vimeo").show();
}
}
At the moment, I have to enter the course id, to make it work. What i want is to be able to derive the course type dynamically. So essentially i would like to do something like this in javascript
if(event.target.value == course.physical? )
How I can remove the video form input dynamically with Javascript when the value of the course is a 'physical' course_type.

Display only three inputs in your dropdown using selectize.js

I am using selectize.js for a nice dropdown, however I'm trying to show only three results when its dropped down instead of the full 20 that I've got. Thus, when a user wants to find something he needs to type unless they are one of the first three. I'm still new to Javascript and I couldn't find an answer in other questions that helped. I've put my relevant code below. Thank you so much!!
HTML
<div class="field">
<%= f.label :homecity, "Home Town" %><br>
<%= f.select :homecity_id, Homecity.all.pluck(:Hometown, :id), {}, { class: "selectize1" } %>
</div>
Edit.js
$(document).on("turbolinks:load", function() {
var selectizeCallback = null;
$(".homecity-modal").on("hide.bs.modal", function(e) {
if (selectizeCallback != null) {
selectizeCallback();
selecitzeCallback = null;
}
$("#new_homecity").trigger("reset");
$.rails.enableFormElements($("#new_homecity"));
});
$(".selectize1").selectize({
create: function(input, callback) {
selectizeCallback = callback;
$(".homecity-modal").modal();
$("#homecity_Hometown").val(input);
}
})
});
selectize takes an option parameter for "maxOptions" that provides what you want.
for example:
$(“.selectize1”).selectize({maxOptions: 3});

linking textbox with dropdown menu

I am writing a program which consist of a drop down menu and it consist of few default values as below:
<%= f.select :securtiy_question, options_for_select([["Select a question.."],
["What is your previous cell number?"], ["What is your fathers name?"], ["write your question"]]),{}, :onchange => 'CheckOther(this);' %>
the HTML output of this is:
<select id="user_securtiy_question" name="user[securtiy_question]" onchange="CheckOther(this);"><option value="Select a question..">Select a question..</option><option value="What is your prevoius cell number?">What is your prevoius cell number?</option><option value="What is your fathers name?">What is your fathers name?</option><option value="write your question">write your question</option></select>
I wanted to display a textbox when I click "write your question" in drop down menu. For that purpose I have made an empty textbox with display as none.
<%= f.text_field :own_ques, :style => "display: none;"%>
Now I make a JAvascript in my view itself:
<script type="text/javascript">
CheckOther = (user_securtiy_question) -> if user_securtiy_question.selectedIndex is user_securtiy_question.options_for_select.length - 1 document.getElementById("user_own_ques").style.display = "inline" else document.getElementById("user_own_ques").style.display = "none" document.getElementById("user_own_ques").value = "" return </script>
But still I am not able to see the textbox appearing someone please come up with a solution...
You can use a simple jquery in the page.
$("#user_securtiy_question").change(function(){
$("#user_own_ques").val('');
if(this.val()== "write your question"){
$("#user_own_ques").show();
}else{
$("#user_own_ques").hide();
}
});

Rails, Send id to URL via Javascript

I have a collection select, and I am trying to refresh the page, and pass the org_id to the URL when the user chooses from the collection select. The collection_select looks like this...
<div id="org-select">
<%= collection_select :org, :id, Org.all, :id, :name %>
</div>
In application.js I have...
$(document).ready(function(){
$("#org-select").on("change","select",function(){
val = $(this).children('option:selected').val();
window.location = '/sessions?org_id='+ val;
});
});
When the user chooses a new org from my coll_select, I am getting a page refresh. However, my URL looks like..
http://localhost:3000/sessions?org_id=2
The org_id ($this.val()) is getting set to 2 each time. It is not being updated when I choose a new org from my drop down. The page is updating, but the id is set to 2 each time.
Here is the rendered HTML...
<div id="sessions">
<div id="org-select">
<select id="org_id" name="org[id]"><option value="1">Lumbees</option>
<option value="2">Tuskarora</option></select>
</div>
The issue I am seeing now is that the page defaults to 'Lumbees' being selected in my dropdown, and even when I choose another value, the page redirects back to 'Lumbees'. Any ideas? Obviously there is a redirect somewhere, however there is nothing in app/views/sessions/index.html.erb that I can find.
what is your collection select id,i guess it org_id or write some custom id ,you are making request on change of div which is incorrect.
<div id="org-select">
<%= collection_select :org, :id, Org.all, :id, :name,{},{:id=>"org_id"} %>
</div>
$("#org_id").on("change", function(){
window.location = '/sessions?org_id='+ $(this).val()
});
Your are trying to pick an value from the div element which should not work.
If you listen on the select element insted it should work better.
$(document).ready(function(){
$("#org-select select").on("change", function(){
window.location = '/sessions?org_id='+ $(this).val()
});
});
And if it still don't work you cud also try to be more precise with the selected value like below.
$(document).ready(function(){
$("#org-select select").on("change", function(){
window.location = '/sessions?org_id='+ $(this).find(':selected').val()
});
});
try next:
UPDATED
$(document).ready(function(){
$("#org-select").on("change","select",function(){
val = $(this).children('option:selected').val();
window.location = '/sessions?org_id='+ val;
});
});
The issue with the page refresh was in the collection select...here is all the code...
app.js
$(document).ready(function(){
$("#org-select select").on("change",function(){
val = $(this).val();
window.location = '/sessions?org_id='+ val;
});
});
index.html.erb
<%= collection_select :org, :id, Org.all, :id, :name, {:selected => params[:org_id]} %>
I needed to specify an object to be selected by default.

Categories

Resources