Reading a model attribute value using Java in JSP - javascript

I'm basically trying to assign my model attribute value to a Java string variable. I googled some things and I used this method below:
<input type="hidden" id="businessNameId" name="businessNameId" value="${business.business.name}">
<% String businessName = request.getParameter("businessNameId");
if(businessName.contains("- [")){ %>
<p class="industry-title">Restaurant Location</p>
<%}%>
I also tried the attribute method which is:
<% String businessName = (String) request.getAttribute("business.business.name");
if((businessName).contains("- [")){ %>
<p class="industry-title">${business.business.address.city}</p>
<}%>
Still doesn't work.
Although this does not seem to work, basically the variable business Name is not being initialized. I need to use Java in this case.

If your value is in an attribute and not a parameter, then you can access it using:
<% String businessName = (String) request.getAttribute("businessNameId") %>
If this doesn't work, you should check that businessNameId is indeed in the parameters, for example using:
<%# page import = "java.util.*" %>
<%
Enumeration in = request.getParameterNames();
while(in.hasMoreElements()) {
String paramName = in.nextElement().toString();
out.println(paramName + " = " + request.getParameter(paramName));
}
%>

Related

How to access changing instance variables (due to a loop) in JavaScript

I am trying to use AJAX to append images to a div container. My photos have a URL field, and so I tried to create an instance variable to then throw inside a div tag like <div id="individual-photo" data-url="<%= #photo_url %>">.
This didn't work, because it assigned one value for that instance variable and when I called it in my .js var url = $("#individual-photo").data("url");, it gave me the same image for all future photos.
I found that solution in another StackOverflow and I think that would work if I wasn't working with a div generated through a loop.. so my question is, seeing as how I am using a loop.. how do I communicate this information to my .js file?
This is the code in my index.html.erb
<div id="sidescrolling-container">
<% if #page > 1 %>
<%= link_to "PREV", (next_path(#link - 2) + "/#individual-photo") %>
<% end %>
<% #pics.each do |photo| %>
<% #pic_id = photo.id%>
<% #photo_url = Photo.where(id: #pic_id)[0].url %>
<div id="individual-photo" data-url="<%= #photo_url %>">
<img src="<%= photo.url %>" height='250px' width="250px">
<span id="photo-title"><%= photo.title %></span>
</div>
<% end %>
<% if #page < #page_max %>
<%= link_to "NEXT", (next_path(#link) + "/#individual-photo"), id: "next_button" %>
<% end %>
</div>
and my .js
var images = $.get("photos/" + page, function(data){
var info = $("#individual-photo", data).each(function(){
var title = $("#photo-title", this).text();
var url = $("#individual-photo").data("url");
$("#sidescrolling-container").append(
'<div id="individual-photo"><img src="'+url+'" height="250px" width="250px"><span id="photo-title">'+title+'</span></div>'
)
})
})
If there's a better way to go about this I'd love to know more! Just no gem solutions please, I don't want to use gems for this part of my code.
$("#individual-photo") references every individual photo in your complete DOM, $("#individual-photo").data() always references the data properties of the first element in this selection. Therefore, you always get the the first url.
It should be
var images = $.get("photos/" + page, function(data){
$("#individual-photo", data).each(function(){
var title = $("#photo-title", this).text();
var url = $(this).data("url");
$("#sidescrolling-container").append(
'<div id="individual-photo"><img src="'+url+'" height="250px" width="250px"><span id="photo-title">'+title+'</span></div>'
)
})
})

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!

How to pre-populate dynamically added form inputs in Rails

I have an edit.html.erb form for #profile instances. Normally when I load the form, the inputs inside the form are pre-populated with the corresponding attribute of the instance.
e.g. <%= f.text_field :name %> would pre-populate its value from #profile.name.
I would like to add additional fields on runtime using jQuery that allows users to input additional data with additional dynamically added inputs.
i.e. #profile.subjects is a hash containing the subjects and their descriptions (for example it could be {"math" => "I teach calculus", "science" => "I have a physics degree"} )
I retrieve a list of subjects from #profile.subjects, and insert textarea elements into the form for each subject using append() in jQuery.
So if #profile.subjects contains "math" and "science", I would do the following in jQuery:
var subject = *string containing subject*;
parent.append("<textarea id='profile_" + subject + "_desc' name='profile[" + subject + "_desc]'></textarea");
This would imitate creating the fields <%= f.text_area :math_desc %> and <%= f.text_area :science_desc %> to my knowledge.
However, when I pass in the attributes math_desc and science_desc to the instance variable #profile in my controller, the inputs do not pre-populate with their values unlike the static form inputs.
I can access #profile.math_desc and #profile.science_desc in the view, but I would like the inputs to have these values upon the view loading.
I do not know how I would add ruby variables to the append() argument with a variable as the attribute name.
e.g. append("<textarea><%= #profile.send('math_desc') %></textarea>") works, but append("<textarea><%= #profile.send('" + subject + "_desc') %></textarea>") does not.
EDIT 1:
Here is how I assigned additional attributes to my instance:
# NOTE: #profile.subjects contains a string representation of {"Math" => "I teach calculus", "Science" => "I have a physics degree", ...}
def edit
#tutor = current_tutor
#profile = #tutor.profile
# Call method to parse subjects JSON
subject_parsing(#profile)
end
private
# Decode JSON subject field into a hash
def subject_parsing(profile)
unless profile.subjects.blank?
# Decode subjects into a hash
parsed_subjects = ActiveSupport::JSON.decode(profile.subjects)
# Extract subject names from hash into a string separated by commas
profile.subject_names = parsed_subjects.keys.join(', ')
parsed_subjects.each do |subj, desc|
subj = subj.downcase
profile.class_eval do
attr_accessor "#{subj}_desc"
end
profile.send("#{subj}_desc=", desc)
end
end
end
So my workaround was to use the gon gem to send a Rails hash to Javascript then calling the subject descriptions according to the subject_names array.
Added this to the controller (see EDIT 1 code)
# Decode JSON subject field into a hash
def subject_parsing(tutor_profile)
unless tutor_profile.subjects.blank?
# Decode subjects into a hash TODO: change this because it is very slow
gon.subjects = ActiveSupport::JSON.decode(tutor_profile.subjects)
# Extract subject names from hash into a string separated by commas
tutor_profile.subject_names = gon.subjects.keys.join(', ')
end
end
Then ended up with this in the Javascript:
var subjectNamesInput = $('#tutor_profile_subject_names');
// Initialize subject description input boxes
$.each(subjectNamesInput.tagsinput('items'), function(i, subject){
updateSubjectInputs(subject, 'add');
});
function updateSubjectInputs(subject, action){
var parent = $('#subject-description-inputs');
var subject = escape(subject);
var text = "";
if (gon.subjects[subject] != undefined)
text = gon.subjects[subject];
if (action == 'add'){
parent.append("<textarea id='tutor_profile_" + subject.toLowerCase() + "_description' name='tutor_profile[" +
subject.toLowerCase() + "_description]' class='form-control form-text-area' rows='5' placeholder='Add some detail about your experience with " + subject +
" (optional)'>" + text + "</textarea>");
}
else if (action == 'remove'){
$('#tutor_profile_' + subject.toLowerCase() + '_description').remove();
}
}
This was in my view:
<%= f.text_field :subject_names, class: 'form-control tagsinput typeahead', placeholder: 'Subjects you teach' %>
<div id="subject-description-inputs">
</div>

how do i access the document dom object in ejs?

I am trying show a list of participants when the user clicks on the button.But each time i end up with an error ""document is not defined".(Please don't give me jquery!!).
<% var bt = document.getElementById("bt");
bt.addEventListener('onclick',function(){
var chatbox = document.getElementsByClassName('parti');
var msg = document.createElement('div');
msg.setAttribute('class', 'participants');
msg.textContent('Participant \n\n\n'); %>
<%= chatbox.appendChild(msg); %>
<% }); %>
Change this line:
bt.addEventListener('onclick',function(){
With this:
bt.addEventListener('click',function(){
When we use addEventListener we don't need to use prefix 'on' for even name.
Also, you have used getElementsByClassName and for this you need to iterate over array, so use:
<%= chatbox[0].appendChild(msg); %>

How can I send an automatically generated ID for a form element to a javascript function?

I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.
I tried doing it this way:
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !#id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
.. But since I don't know the ID of the element, I can't call it from the function.
So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!#id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either
A) get the element ID from the field to the function in the first option, or
B) call this function from this input element whenever it loads?
... or C) an alternative way to do this?
Thanks in advance and let me know if more details would help.
If you have ID saved in the model, get it with <%= model.id %>
Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.
If you have it somewhere on the page :/ then you can use jQuery to get it for you.
< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >
$("#id_of_the_element").attr('attr_with_my_id')
< input id="id_of_the_element ... >< /input >
$("#id_of_the_element").value

Categories

Resources