Apologies if this is answered elsewhere, please point me in that direction.
Using Node and EJS, I have a form field for capturing the name of a brewery, this comes via an API...
<label>Brewery</label><br>
<input id="formBreweryName" class="form-control" type="text" name="breweryname" ><br>
<label>Beer Name</label><br>
<input id="formBeerName" class="form-control" type="text" name="beername" >
Here's the ejs that both displays the brewery name in a <ul> and contains the onclick handler for populating the form...
<ul>
<% BeerList.forEach(function(objsofbeer){ %>
<li>
<a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
<span><%= objsofbeer.brewery.brewery_name %></span><br>
<span><%= objsofbeer.beer.beer_name %></span><br>
</a>
</li>
</ul>
And the javascript for porting the brewery name up to the form...
var addFormText = function( breweryName, beerName) {
document.getElementById('formBreweryName').value = breweryName;
document.getElementById('formBeerName').value = beerName;
}
the API passes me a brewery name like so...
brewery_name: 'Reuben\'s Brews',
I added the beer name in the code above for good measure.
The Issue
When there is an apostrophe in the brewery name, the brewery name will not show in the appropriate form field, BUT the brewery name does show in the section.
For most examples, the brewery name does not have an apostrophe. So the API brewery name shows up in the form field as expected. But as in the example above, the brewery name has an apostrophe, so the name will not show up in my form field.
I am hoping there is a non-javascript, pattern attribute solution that will let me optionally include apostrophes (or other unforeseen special characters) in the text. If not, then I'm open to javascript or other suggestions.
I see many examples of 'use pattern to exclude certain characters' or 'use pattern to force users to only use this given text pattern'. But I don't see anything that would allow for the optional inclusion of a character like an apostrophe (or any other optional inclusion of special characters).
If it seems like this is an issue beyond my form input field, I am happy to share more of my coding.
Not sure but i think the problem is that you need a double escape character before the accent, one for the ejs on the server and one for the js on the browser. Can you try using <%- instead of <%= (EJS doesn't escape characters).
Sorry i never used ejs... other try, very ugly...:
<ul>
<% BeerList.forEach(function(objsofbeer){ %>
<% objsofbeer.brewery.brewery_name = objsofbeer.brewery.brewery_name.replace("'","\\'"); %>
<% objsofbeer.beer.beer_name = objsofbeer.beer.beer_name.replace("'","\\'"); %>
<li>
<a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
<span><%= objsofbeer.brewery.brewery_name %></span><br>
<span><%= objsofbeer.beer.beer_name %></span><br>
</a>
</li>
or try playng with ` character instead " or '
Related
I am fairly new to full stack development and I am trying to get a simple search form to work. The webpage is supposed to redirect the user to a page with a list of all videos containing the keyword. Whenever I type in a title that exists, I get :NoMethodError at /posts/:title/search
I've tried using a query but have failed.
This is my app.rb. I query all videos that contain :title.
get "/posts/:title/search" do
# authenticate!
#results = Video.all(title: params[:title])
if #results
erb :search_success
else
flash[:error] = "Video not found."
erb :search_success
end
end
This is search_success.erb where I want to have a list of the videos that contains the keyword in the title.
<div class="container">
<% #results.each do |r| %>
<h1><%= r.title %></h1>
<% end %>
</div>
This is navigation.erb where the search form lives.
<form action="/posts/:title/search" method="get">
<input type="text" type="text" placeholder="Search" aria-label="Search">
<button type="submit">Search</button>
</form>
Try changing
#results = Video.all(title: params[:title])
to
#results = Video.all(:title.like => "%#{params[:title])}%")
to get answers that don't need to match completely (i.e. match case etc.)
Also in your search form, you have two type attributes. You should change one of them to
name="title"
I'm trying to set up a webapp using Sinatra, and I've got it working currently where the user can enter a list of URLs into a textarea, click submit, and then some code is ran on the URLs and the user is redirected to a second page to view the result. I'd like to remove the redirection and display the results in another textarea on the same page(or even re-use the same text area) but I've so far been unsuccessful in this venture. Instead of displaying the result, the second textarea just displays the <%=res%> and the submitted URLs disappear.
ERB page
<h1>Put URLs Here</h1>
<form method="POST" action="">
<p><textarea id="urls" name="urls" rows="20" cols="60">
</textarea></p>
<input type="submit">
</form>
<br />
<br />
<h1>Results</h1>
<p><textarea id="results" name="results" rows="20" cols="60">
<%=res%>
</textarea></p>
app.rb
require 'sinatra'
get '/ip' do
erb :ip
end
post '/ip' do
res = Hash.new("")
u = params[:urls].lines("\n")
list = Ipcheck.new()
res = list.check(u)
erb :ip, :locals => {'res' => res}
end
What am I doing wrong? I've searched and have not been able to find a solution to this specific problem.
Use global variable instead of local.
<%= #res %>
and
#res = Hash.new("")
u = params[:urls].lines("\n")
list = Ipcheck.new()
#res = list.check(u)
erb :ip
I am trying to display the search query in the search bar in HTML.
But if the variable includes a space, the webpage is only going to display the first word.
Here is the code
app.get('/search', function(req, res) {
console.log(req.originalUrl,'oro')
console.log(req.query['search_query'],'aaaaaaa')
res.render('search.ejs', {
user : req.user,
query : req.query['search_query']
});
});
Here is the html code
<form action="/search" method="get">
<div class="form-group">
<input type="submit" class="btn btn-warning btn-lg" value = "search" style = "float: right"/>
<div style="overflow: hidden; padding-right: .5em;">
<input type="text" value = <%= query %> class="form-control" name="search_query" style = "width:100%;"/>
</div>
</div>
</form>
query is the variable collected from the last webpage and passed to /search.
If I type in "I want to find xx", the webpage will only display "I" in the search box. However, in the console, the printout result is the full query " I want to find xx". The corresponding url is also correct "/search?search_query=I+want+to+find+xx".
Anyone has an idea? Thanks a lot!
Let's start with correcting your HTML, by using quotes in value:
<input type="text" value = "<%= query %>" class="form-control" name="search_query" style = "width:100%;"/>
Here under IE you should see a large error, on FF and Chrome browser will try to save the situation and catch only the first word.
Prolably rest of your words are used as attributes and ignored in this input.
Change <%= query %> to <%- query %> .
To add a new line or space while working with ejs, you will have to replace string parameters with HTML tags.
For example, here, I am replacing \n => < br/> to add a new line
<% var testVar = 'Line1\nLine2' %> <%- testVar.replace(/\n/g, '<br/>') %>
Change <%= query %> to <%- query.replace(/ /g, " ") %>
I struggled for hours to render text with spaces
Adding quotes seems to be the easiest solution to this
value = "<%= query %>"
to solve partial content change:
<%= to <%-
use: `` with "" inside
JS example:
let txt = "some text"
console.log(`"${txt}"`)
Thanks for any help you can provide! I have a Ruby on Rails application where I am trying to save maps with driving directions and waypoints. The data needs to come straight out of the entry form instead of the Google Maps javascript. I've solved the starting and ending points, but the waypoints are giving me a problem.
My questions:
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
How can I make each waypoint.newsavedmap_id field the same as its corresponding newsavedmaps id so that I can call these up later?
HTML
<p>Enter a street address, city, and state:
<input id="startinput" type="text" name="starthere" size="56"></p>
<p>Or, select a location from the list:
<select id="startdrop" name="startthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
<div><b>Stops</b></div>
<div id="multiselectdiv1">
<select multiple id="waypoints" name="waypointsselected">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select>
</div>
<b>End</b>
<p>Enter a street address, city, and state:
<input id="endinput" type="text" name="endhere" size="56"></p>
<p>Or, select a location from the list:
<select id="enddrop" name="endthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
</div>
<div>
<input type="submit" onclick="calcRoute();" id="showmapview" value="Show Map">
</div>
I have two MySQL tables. The first is newsavedmaps:
id
itinerary_id
start
start_lat
start_long
start_masterlocation_id
end
end_lat
end_long
end_masterlocation_id
name
The second is waypoints:
id
newsavedmap_id
waypoint
waypoint_lat
waypoint_long
waypoint_masterlocation_id
The two are meant to be connected by newsavedmaps.id and waypoint.newsavedmap_id .
My newsavedmap_controller.rb includes:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
if !params[:starthere].blank?
#newsavedmap.start = params[:starthere]
else
#newsavedmap.start = params[:startthere]
end
if !params[:endhere].blank?
#newsavedmap.end = params[:endhere]
else
#newsavedmap.end = params[:endthere]
end
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
end
Edit 1
In response to Colinm's suggestion to wrap the controller in an iterator to get separate records for each address, I tried this, but I'm pretty sure I'm doing the wrong thing:
if !params[:waypointsselected].blank?
for waypoint in #waypoint
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
#waypoint.newsavedmap = #newsavedmap
end
end
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
Unless you have a really good reason not to, use Rails' form helpers instead of rolling your own form fields. They will take care of this automatically, as well as handle edge cases you may not even know about. (Like the gotcha that sending a multiple select back with no selections will leave the record unchanged. That doesn't sound like it's an issue in your use case, but Rails still has your back if you use the form helpers.)
In your case, you'd simply pass multiple: true in the html_options hash, like so:
<%= f.select :waypointsselected,
MasterLocation.waypoints_for_select,
{},
{ multiple: true }
%>
Note that this does assume you implement a waypoints_for_select method. Without seeing all the code, it looks like you have way too much logic in your view right now. It's brittle and verbose to construct the options array in the view; offloading that to the model or a helper keeps your view code cleaner and helps eliminate potential future bugs.
If you absolutely can't/absolutely don't want to use form helpers in this application, the key you're looking for is []. Rails sensibly assumes a form field represents a single value unless you explicitly denote it as an array. Just tack an empty array on the end of the field name:
<select multiple id="waypoints" name="waypointsselected[]">
...and that field's key in the params hash will instead contain an array of values representing the selected items:
{ waypointsselected: ["3", "6", "9"] }
As for associating the waypoints with the newsavedmaps, just set it explicitly during creation. You're almost there:
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
# You can do it like this...
#waypoint.newsavedmap = #newsavedmap
# Or using the ID...
#waypoint.newsavedmap_id = #newsavedmap.id
end
(I haven't adapted this code to deal with the fact you now have an array of values in waypointsselected; I just plugged the relationship definitions into your existing code. Remember to adjust your code to expect an array and iterate over it.)
I'm trying to generate a link using the link_to helper that will output the following HTML:
<i class="some_class"></i>Link Name
However the code I'm using to try to accomplish this:
link_to(tag("i", class: options[:icon]) + title, url)
...is outputting:
<i class="some_class">Link Name</i>
Why is it doing this, and how can I fix it? Thanks.
EDIT:
I believe I found the issue.
<i> tags are not self-closable tags in HTML5. Therefore the text after the i is treated as that element's content.
Have you tried using the block format of link_to?
<%= link_to url do %>
<%= tag("i", class: options[:icon]) %>
Link Name
<% end %>
Tweak that to your needs and maybe you'll get what you're looking for.
This is the icon tag helper I use in my applications which I frequently pass as the first argument to link_to, which can either be used to create a icon tag alone, or an icon tag followed by text.
def icon_tag(icon, *args)
options = args.extract_options!
text = args.first || options.delete(:text)
if text.nil?
content_tag :i, "", class: ["icon", "icon-#{icon}"] + options[:class].to_a
else
"#{icon_tag icon} #{text}".html_safe
end
end