linking textbox with dropdown menu - javascript

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();
}
});

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?

Rails: Making each choice in a form select field render relevant input in another form field

Noob here so I apologize ahead of time for sounding like an amateur. I'm trying to code an e-commerce site. Customers will order posters from images uploaded to the site and get to choose the size of poster (h x w) they want depending on the dimensions of the original image. I have a form for creating a new order and one of the fields is a select field with the poster size options. When they select a size, I want a price to automatically update in a separate field in the form so they know before submitting the form what the price will be.
The strategy I've been trying is to add jQuery onclick code in the select field choices. Here's what I have for the form (just showing the first choice in the select field for brevity):
<%= form_for(#order) do |f| %>
<div id="order_form">
<div class="field">
<%= f.label(:size) %><br>
<%= f.select(:size, [link_to("#{#image.dimensions['width']/120} * #{#image.dimensions['height']/120}", '#', :onclick => "showPrice('#{#image.dimensions['width']/120} * #{#image.dimensions['height']/120}'); return true;"), ... ]) %>
</div>
<div class="field">
<%= f.label(:price) %><br>
<%= f.text_field :price, :id => 'price' %>
</div>
</div>
And in assets>javascripts>application.js my jQuery code is:
function showPrice(size) {
$("#price").html("$" + size * 0.08);
}
It's not working and I don’t know if what I’m trying to do won’t work or if I'm just doing it wrong.
Thanks in advance for any help.
Here's the solution I came up with finally... I changed my goal a little, instead of trying to make it so when the user selects the size it will automatically update the price field I just made a separate paragraph (not a form field). Here's what it looks like:
<div id="order_form">
<p id='price'><%= '$' + :size.to_int * 0.8 %></p>
<div class="field">
<%= f.label(:size) %><br>
<%= f.select :size, ["#{#image.dimensions['width']/120} X # {#image.dimensions['height']/120}", "#{#image.dimensions['width']/140} X #{#image.dimensions['height']/140}", "#{#image.dimensions['width']/160} X #{#image.dimensions['height']/160}", "#{#image.dimensions['width']/180} X #{#image.dimensions['height']/180}", "#{#image.dimensions['width']/200} X #{#image.dimensions['height']/200}", "#{#image.dimensions['width']/220} X #{#image.dimensions['height']/220}"], {}, :oninput => "showPrice(this)" %>
</div>
</div>
and here's my jQuery function:
function showPrice(size) {
var Amt = $(size).val();
var arr = Amt.split(" ");
var newerAmt = Math.round( arr[0] * arr[2] * 0.8);
$("#price").html('Price: $' + newerAmt);
}
This works except it's not automatically showing the price when the page with the form loads with the default size... any advice on that would be great...
~~~~~~~~~
OK I finally figured that last part out. I referred to another thread on here and it led me to this solution so sorry for the resubmit but here it is:
To get JavaScript to recognize the ruby symbol :size I added this div in that same file:
<%= content_tag :div, class: "size_information", data: {size: #size} do %>
<% end %>
It isn't visible in the browser but it contains the data we need for JS.
Then in the JS function on that same page I referred to that data and then was able to use it as a variable:
<%= javascript_tag do %>
$(document).ready(function() {
var size = $('.size_information').data('size');
var arr = size.split(" ");
var newerAmt = Math.round( arr[0] * arr[2] * 0.8);
$("#price").html('Price: $' + newerAmt);
})
<% end %>
I would try something like this.
$('select#size').change( function () {
var amount = $('select#size').val();
var newAmt = amount * 0.08
$('#price').val('$' + newAmt);
})
Try breaking down the parts of the code to see which is working and which are not.
For example start with something simple like this
$('select#size').change(function () {
var amount = $('select#size').val();
console.log(amount)
//checking to see if .change function works
//and if you are able to collect the value of
//whats inside 'select#size'
})
If this works then maybe you can consider doing the next line
var newAmt = amount * 0.08
console.log(newAmt)
If this works then next would be to try checking to see if you are successfully calling on the #price field.
var price = $('#price').val();
console.log(price)
So if thats working then maybe you can try placing values into #price first
$('#price').val('its working!')
If all of them are working, combining the whole code should work too. Hope this helps!

Ruby on Rails reset value back to null

Following were my view:
<div class="col-xs-3">
<%= f.select(:require_booking, get_advance_booking.collect {|p| [ p[:require_booking], p[:require_booking] ] }, {include_blank: false} , :class => 'form-control') %>
</div>
<div class="col-xs-3">
<%= f.text_field :require_days, :class => 'form-control advance-booking', :placeholder => 'How many days?', :disabled=>true%>
</div>
And here is my application_helper.rb
def get_advance_booking
ret = [{:require_booking => 'Yes'},{:require_booking => 'No'}]
end
Following were my product.rb model
class Product < ActiveRecord::Base
enum require_booking: {
No: 0,
Yes: 1
}
end
Now the Issues is if I select an option of Yes the text field will be enabled and user can enter value. In edit mode, if I select an option No how can I set the text field value back to NULL and save to db? Currently, even though I set the value NO I still get my previously set value. Thanks!!
You only can do that with javascript changing the value field of select.
Example:
Supose that your code generate the following html:
<input type="select" value="Yes"></input>
<input type="text" value="EditValue"></input>
For solve this question you need a javascript(jQuery) code like this:
$("input[type='select']").change(function() {
$("input[type='text']").val(' '); });
Actually, you cant assign Null value to the form input. You can set it to be empty '' . But that wouldn't not be helpful in your case. The possible solution for you is to disable the field when 'No' is selected. Disabled input value would not be submitted in form. So the base case would be handled.
But if you are updating than you can handle it on the backend. You can add before filter.
before_filter: check_for_require_days
def check_for_require_days
params.merge!(require_days: nil) unless params[:require_days].present?
end
This would check if the value is disabled than it would not be in the form params so it would set it to null.
Just add :onchange => "$('#product_require_days').val('')" to your "require_booking" select
<%= f.select(:require_booking, get_advance_booking.collect {|p| [ p[:require_booking], p[:require_booking] ] }, {include_blank: false} , :class => 'form-control'), :onchange => "$('#product_require_days').val('')" %>

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

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);
});

pass selected drop down value as params in rails link_to

I have a select tag which populates list of department names, When I select a value from drop down, I need to display an edit link below (link_to) and append the selected value of dropdown as id params.(I am not using form for this single select tag since I dont need to save value in my databse). How this could be possible. Please help. I am using rails2.3
I tried like the below but it didn't work.
Select A Dept
<%=select :select_dept, :dept, #dept.map{|dept| [dept.full_name, dept.id]},{:prompt => "#{t('select_a_batch')}"} %>
<%= link_to "Display", {:controller => "user", :action => "display_value", :id => $('#select_dept').val() } ,:class => "button" %>
Gopal is on the right track.
Give the link an id so you can pick it out
<%= link_to 'Display", {:controller ...}, :class => 'button', :id => 'display_link' %>
Hide it with CSS by default
#display_link { display:none; }
#display_link.showing { display:block; }
Then in javascript, do something like
$('#select_dept').on('change', function(ev) {
var deptId = $(this).find(':selected').val();
var newPath = '/users/' + deptId + '/display_value';
$('#display_link').attr('href', newPath);
$('#display_link').addClass('showing');
});
This will not set things up on page load, but you could run the same function you've passed as the change callback on page load to set things up (assuming one of the items might be selected on load).

Categories

Resources