Retrieving the value of select option in Servlets - html

I have a select tag in my form which is to be send to Servlet. I have made the contents of the select tag dynamic(it gets values from a table column in DB).
Select Branch:-<select>
<%
while(r.next()){
%>
<option><%=r.getString("code")%></option>
<%
}
r.close();
s.close();
con.close();
%>
</select>
('r' is ResultSet)
My problem is how can i send the value the user has selected from select tag to servlet. For using Request.getparameter("name") I must know the value of option tag.
I my confused.Please help..
Thanks.

Assign a unique name to select tag. <select name="codeSelect">
However, this isn't the right way to approach this, perform all the database interaction in Servlet and set appropriate request parameter and forward it to jsp.

<select id="codes">
<%
while(r.next()){
%>
<option value="<%=r.getString("code")%>"><%=r.getString("code")%></option>
<%
}
r.close();
s.close();
con.close();
%>
</select>
Now, you can get the value of 'codes'

Related

Populate an HTML DropDown List with data from mysql database without PHP

I'm currently building a rails app where im trying to fetch data from different tables from my sql database and I need to put that fetched data (id, first_name, last_name) into an HTML Drop-down where the user is going to select between all possible choices, for exemple:
DROPDOWN Clients:
default: --SELECT--
1 Thomas Carrier
2 Michel Carrier
3 Yvon Dupuis
So if we take the first choice, 1 is the id of the first employee, and his first name (Thomas) and last name (Carrier)
I keep finding stuff about php but I cannot use php!
Thanks for the help
this is another option which I think is more the "rails" way:
You should add this to your client.rb model:
def full_name
first_name + ' ' + last_name
end
and then in your view something like this:
<%= select_tag("clients", options_from_collection_for_select(#clients, "id", "full_name"), include_blank: '--SELECT--') %>
The easy answer
plain html
<select name="clients">
<option value="1">Thomas Carrier</option>
<option value="2">Michel Carrier</option>
...
</select>
or with ruby (https://guides.rubyonrails.org/layouts_and_rendering.html)
<select name="clients">
<% #clients.each do |client| %>
<option value="<%= client.id %>"><%= client.firstName %> <%= client.lastName %></option>
<% end %>
</select>
Also refer to Yaniv Iny's answer to for a better more correct way

Submit a 'null' to a jsp from an html form

Forwarding an html form to a jsp page which has an
<input type="text" name="name">
for 'name' parameter to be processed in jsp page. When no name is supplied , I do want the form to be submitted to the jsp and jsp should detect 'null' to process an if-else loop to display a relevant message.
How do I achieve that?
I do want the form to be submitted to the jsp and jsp should detect
'null' to process an if-else loop to display a relevant message.
You can use this on your display.jsp page to check if value is not null and not empty:
<%
String name = request.getParameter("name");
if(name != null && !name.isEmpty()){
%>
<p>name is <%=name%></p>
<%
}else{
%>
<p>name is null or empty!</p>
<%
}
%>
But as mentioned already this is highly discouraged! You should be using a servlet. If you want to see how that can be done, let me know and i'll edit this answer with a better solution.

How to display pre-selected(default) value in drop down list according to the value fetch from database in jsp?

I have a jsp page in which there is a drop-down list. The options in the drop down list comes from database. I need pre-selected option in the drop down list according to the value fetched from database by sql query.
Here is my code for jsp which has a drop down list and which fetches options from database.
<select class="form-control col-sm-7" name="leavedropdown" style="width: 31% ; margin-right:-20%" >
<option>--Select Group--</option>
<% Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con17=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl","system","system");
PreparedStatement psmt17= con17.prepareStatement("SELECT DISTINCT * FROM LEAVE_TYPE");
ResultSet rs17=psmt17.executeQuery();
while(rs17.next()) {
%>
<option value="<%= rs17.getString(2)%>"><%= rs17.getString(2)%> </option>
<% } %>
</select>
Now I wrote this code above the current select tag to fetch value of a record which should be pre-selected in drop down list
PreparedStatement psmt18= con18.prepareStatement("SELECT DISTINCT LEAVE_TYPE FROM EMPLOYEE_LEAVE where lid='LV00001'");
ResultSet rs18=psmt18.executeQuery();
%>
How should I use this value to match into drop down list and display it as pre-selected option in it?

options_from_collection_for_select doesn't save first value in dropdown

I'm trying to populate a dropdown menu with values from the database.
I'm using:
options_from_collection_for_select
The goal is to display a value in the dropdown that will correspond to the user id for that row in the database and when selecting a value the id for that value will be saved.
I'm able to populate the dropdown menu with values and save successfully. The problem is that the first value in the dropdown menu is saved as-
"<option value=>"
instead of just saving the id (see html source below) . All other values are saved correctly.
How can I make the first value behave like the others?
This is the code:
<% options = options_from_collection_for_select(#landlord, "id", "company_name") %>
<%= f.select :landlord_name, [[:all_val, options], ["Other", "Other"]]
, prompt: "Select...", class: "form-control" %>
This is passed from the controller:
#landlord = Landlord.all
This is the HTML source:
<select name="listing[landlord_name]" id="listing_landlord_name">
<option value="">Select...</option>
<option value="<option value="9">JOJO</option>
<option value="10">SHOOKI</option>">all_val</option>
<option value="Other">Other</option>
</select>
If I understand you correctly, you are trying to populate the select_box with IDs and names from the #landlord collection and add an 'Other' option to the end.
The options_from_collection_for_select method returns HTML strings to be put inside the select tag, populated with the collection names and IDs, so you have to merge the options differently, in a way like this:
<% options = options_from_collection_for_select(#landlord, "id", "company_name") %>
<%= f.select :landlord_name, options + options_for_select([["Other", "Other"]]),
prompt: "Select...", class: "form-control" %>
The code simply appends the collection options string-wise with the output of the options_for_select, which is a general helper for select options, also producing strings to be put into the select tag.

How can I save each item in a "select multiple" field in its own MySQL record (using Rails)?

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.)