jsp submit multiple select - java

I am working in JSP, which I am very new to, and trying to submit values from a select box that can select multiple values to an action class in Java.
<select multiple="multiple" name="ProjectIDs" listKey="projectID" listValue="name" id='lstBox2' style="min-width:150px">
</select>
At the moment I am able to select multiple values and pass the keys to a List variable called 'ProjectIDs' in my action class, which is what I want to do. But I would like to load all of the values in that select box without having to highlight them. This is because the values in the select box are loaded from another select box using javascript and a button that transfers the selected values from that select box to this one. So I shouldn't have to select the values in this select box because I always want to load ALL of them.
What is the easiest way to pre-select all of the values in the select box when I hit the submit button so that I don't have to highlight them myself?
Thank you! And sorry if my explanation was not very clear. I will further explain if this is the case.
Edit: I have made some changes in response to the answer provided. I am also using the Struts framework. So my select box starts out as an empty struts select box, which is then populated from the other struts select box.
<s:select list="#{}" multiple="true" name="ProjectIDs" listKey="projectID" listValue="name" id='lstBox2' style="min-width:150px"/>
Then in my form tag I added this onsubmit function:
<s:form id="formMain" action="performancereport" theme="simple" method="get" onsubmit="selectAllOptions('lstbox2');">
And then finally this javascript function:
function selectAllOptions(selStr)
{
var selObj = document.getElementById(selStr);
for (var i=0; i<selObj.options.length; i++) {
selObj.options[i].selected = true;
}
}
However, I am still having the same problem. If I highlight all the options myself, it works fine, but it is not automatically selecting them for me when I hit the submit button.
Any suggestions?
Edit 2: RESOLVED.

You can programatically select all the options using javascript:
var select = document.getElementById("lstBox2");
for(var i = 0; i < select.options.length; i++)
{
select.options[i].selected = true;
}
You can do this in your onsubmit function...right before you submit the form.

RESOLVED:
I added this jQuery code to occur before the form is submitted.
$(function() {
$('#formMain').submit(function() {
var select = document.getElementById("lstBox2");
for(var i = 0; i < select.options.length; i++)
{
select.options[i].selected = true;
}
return true;
});
});

Related

Changed select on jsp get null value in servlet

I have a jsp page with a number of selects that are populated using jQuery i.e. they have the <option> tags, they just get it via a function. Each select has some 30 options each.
<form id="target" name="target" action="/project/myservlet" method="get">
<select class="myClass" id="sel1" name="sel1" ></select>
<select class="myClass" id="sel2" name="sel2"></select>
...
</form>
I received these values in my servlet using request.getParameter("sel1") but I'm getting null for the selects that are changed. As in, say I select values from the 2nd, 4th and 5th selects, then these selects get null values in the servlet. Others get the 0th value (default and unchanged) - which is okay.
This can help explain my question. I'm getting null in the next page when I modify the select.
According to this, if I use onload in select, it helps take the updated values to the next page for ONE select. But the problem is that I don't just have one select on the page. I want the updated values to go the next page without a page refresh/going to another page, unless submit for them is clicked. I think the request is not getting updated when the change takes place? Even the url in "get" doesn't get the changed selects.
There is no error as such, just that I am getting the values if the selects are unmodified (defaults). It sends the default values to the next page. When I select another option from the drop down, I get null on the servlet unless I use onchangeto submit the form. But that doesn't work for me since I have many selects. I can't keep submitting the form and going to the next page on every select change.
EDIT:
If it helps, here is my jQuery code:
$(document).ready(function() {
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
$('select').each(function(idx,select){
var stateArray = ["Preference No. "+(idx+1),"Bill", "Sally", "Alice"];
$.each(stateArray, function(iIdx, iItem){
$(select).append('<option value="'+iIdx+'">'+iItem+'</option>');
});
});
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
});
});
EDIT 2: Servlet:
public class Preference extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
String sel = request.getParameter("sel1");
}catch(Exception e){ }
}
}
You need to add <option> tags into your <select> tags.
Each <option> must have value attribute like this:
<option value="3">Apple</option>
Value from the value attribute of the selected option will be value of your <select>. You will get it on server-side by name as usual.
The selected options were disabled from all the select elements in my jQuery. I had to modify the jQuery a little. Disabled elements are not carried forward in a form. On modifying the jQuery to not disable the options, the problem was resolved. Had to take a bit of a help to recognize and correct that.

2 submit buttons - different queries,

I have a simple question and I can't find the answer by myself, so here it is.
Let's assume I have one simple index.html in which I have a form with 2 submit buttons. The action to those buttons is mapped to action.jsp. What I want to do is, if I click on the first submit button I want a query of type "SELECT * FROM USER WHERE ID = 1" and when I click on the second submit button I want a query of type "SELECT * FROM USER WHERE ID = 2". Can i do that in a single JSP file? How to do the check whether the first or the second submit button is pressed in the action.jsp - is that possible? Thanks!
Yes you can do both the operations on same JSP page.
Lets say you have two buttons like :
<input type="submit" name="bt1"/>
<input type="submit" name="bt2"/>
Now you can check their button click like :
if(request.getParamater("bt1")!=null)
{
//your first query
}
if(request.getParameter("bt2")!=null)
{
//your second query
}
Also make sure that form action should be the same JSP page on which it is declared
try using 2 forms, 1 form for each button.
or try using button only and create a function to handles it onclick()
Yes , you can use two submit buttons in singleJSP page.
Try this
<INPUT type="submit" name="bsubmit" value="Submit 1">
<INPUT type="submit" name="bsubmit" value="Submit 2">
Now when you create the script, these unique values will help us to figure out which of the submit buttons was pressed.
For example
Following is a sample Active Server Pages script to check for the submit button.
if Request.Form("bsubmit") = "Submit 1" then
btnID = "1"
elseif Request.Form("bsubmit") = "Submit 2" then
btnID = "2"
At server page you can write something like this

populate select box based on the another select box

There are two select boxes ,both of them are populating from database.second select box should be populate based on the value selected from the first select box.first select box is already populated but i am unable to populate the second select box
<select id="country_obj" name="custCountry" class="field_size_e">
<%
Iterator contryIter = countries.iterator();
Lookup lookup = null;
while(contryIter.hasNext()) {
lookup = (Lookup)contryIter.next();
if(bbForm.getCircuit().getCustCountry().equalsIgnoreCase(lookup.getLabel())){
out.print("<option selected=\"selected\" value='"+lookup.getValue()+"'");
out.print(">");
out.print(lookup.getLabel());
out.println("</option>");
}else{
out.print("<option value='"+lookup.getValue()+"'");
out.print(">");
out.print(lookup.getLabel());
out.println("</option>");
}
}
%>
</select>
how do i populate the second select box based on the value of first select box
You can have a function in javascript to populate options for your second select tag.
function populate(val)
{
//val is a string similar to "<option value='new_option'>new option</option><option...</option>..."
$('#my_select2').append(val);
}
//below method is triggered whenever you select a value for your first select box
$("#country_obj").change(function(){
var selected_str = $("#country_obj option:selected").text();
//now pass this selected_str to a php page where options generation method is present using $.ajax (refer http://api.jquery.com/jQuery.ajax/)
//or you can implement the method here (in javascript) to generate options for your new select tag.
}
})
Note: This is just for guidance. You can have implementations of both methods in one or you can have multiple methods. I'll leave that for you to decide.
EDIT: you can't have options generated for your second select tag in the same php page (like in your question) because, by the time your page is loaded and a user selects a value for first select tag your php code is already executed.

Publish an event using Struts 2 jQuery Plugin

I want to use the publish/subscribe framework which is used internally by Strust2 jQuery plugin.
The user can select an account number from a list or type it in a textbox.
I want to publish an event when text box or select option changes. So the user can only type textbox OR select something from select box:
<s:textfield name="account" onblur="$.publish('accountChanged',this,event)"/>
<s:select name="accountList" list="destinationAccounts"
onblur="$.publish('accountChanged',this,event)"/>
Below is the js:
$.subscribe('accountChanged', function(event, data) {
alert("New data is: " + data.value);
if ( event.target.id=='account') {
//Do something
}
}
Here are issues:
The data.value only works for textbox, for select box the data.value is undefined.
I want to know which target received the event. event.target.id is not working! I think the event object is not a jQuery event object?
I reviewed the sample showcase application, but could not find any.
Am I calling $.publish method correctly? Are there better ways?
If you subscribe to topics keep the topic name unique for each tag that allows to separate handlers for the tag. The new event is created each time you publish the topic in the onblur event. The textfield handler for topic works as you described. The select tag doesn't work because wrong parameter passed as the data. The example of the working code
<s:textfield name="account" onblur="$(this).publish('accountChanged', this, event)"/>
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('accountListChanged', this, event)"/>
<script type="text/javascript">
$.subscribe('accountChanged', function(event, data) {
alert("accountChanged: " + data.value);
});
$.subscribe('accountListChanged', function(event, data) {
alert("accountListChanged: " + data.parentElement.value);
});
</script>
As you can see the data.value is undefined because data.parentElement.value should be used. event.target.id is not working because event.originalEvent.target.id should be used. The event object is a jQuery event, but originalEvent is DHTML object which is blur.
I don't know about your requirements, if you need to subscribe/publish events or use the original event handlers, I can't say what is better in this situation.
The below code solved my issue:
As I could not find any example of publish/subscribe framework, I hope below example will help others!
The jsp will be
You must call ${this).publish not $.publish
<s:textfield name="account" onblur="$(this).publish('destinationChanged', this, event)"/>
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('destinationChanged', this, event)" emptyOption="true"/>
<s:textfield name="destinationAccount" type="hidden" />
And the JS will be
$.subscribe('destinationChanged', function(event, data) {
//If user types in the textbox
//then get the value and make the select box shows an empty option
if( !!data.value){
destinationAccount= data.value;
$('#destinationKnownAccount').val($("#destinationKnownAccount option:first").val());
} else{
//The user selected an account from select box.
// So get the value from select box and clean textbox
destinationAccount= data.parentElement.value;
$('#destinationUnknownAccount').val('');
}
//Set the hidden box
$('#destinationAccount').val( destinationAccount);
});
As mentioned one can use event.originalEvent.target.id to find which target was selected.

dynamically update textbox value from database when combobox value is changed

Here is the situation. I have a drop down menu. The option sin this drop down menu are being populated by fetching some values from the database. To do this following is what i have done.. :-
<select name="product_list" onchange="selectProduct(this.value)">
<option value="none">Select one</option>
<%
List<String> options = new ArrayList<String>();
DynamicCombo comboBox = new DynamicCombo();
options = comboBox.generateComboBox();
Collections.sort(options);
int tempVar = 0;
while (tempVar < options.size()) {
out.print("<option value=\"");
out.print(options.get(tempVar));
out.print("\">");
out.print(options.get(tempVar));
out.print("</option>");
tempVar++;
}
%>
</select>
DynamicCombo is a class that has a method called 'generateComboBox()'. This method simply returns an array list containing all the values that are fetched from the database, which is what i need to show in my drop down box in the front end (jsp page). On my jsp page i simply iterate through this list and print it as options appropriately.
This works absolutely fine.
Now i have another text box on my form, say 'textbox1'. Now the requirement is that this text box value should be updated depending on what the user has selected from the above drop down box.
So for example if the user selects 'prod1'(which is a primary key in the backend database table) option from the drop down box, then the corresponding value ( the product name) should be fetched from the database table and should be updated in the textbox named 'textbox1'.
The other thing is this entire thing is contained in a form which is supposed to be finally submitted to the servlet for further processing.
So how can i achieve this.
i figured out the solution to my own problem. It might not be the most elegant way of doing it, but it does the job pretty well.
So as per my requirement, what i exactly wanted to do was.... insert a value (that will be fetched from the database) into a text box on my form depending on what the user chooses from the drop down box that is already present on my form.
To achieve this, i went about and thought if some how i could nest a form withing my main form, it'd solve my issue. But i discovered that nesting of forms is not allowed. So the next option i thought of was to some how submit the same form without the user clicking on the submit button and also handle it appropriately as an 'incomplete' submit (in the sense that the form is still to be submitted manually by the user by clicking on the submit button) on the server.
So i simply made use of the 'onChange' event of a drop down box. I created an additional hidden field on my form.I wrote a simple javascript function that would simply set the value of the hidden field to the string-"partial Submit" and would submit my main form (say named 'form1') as :-
document.getElementById("hidden_id").setAttribute("value","partial submit");
form1.submit;
The function that does the above will be called whenever (and everytime) the onchange event of the drop down box gets fired.
When the user finally clicks on the submit button on the form to submit the finally completed form, then another javascript function is called that simply sets the value of the hidden field on the form to the string, "final submit" and would submit the form as :-
document.getElementById("hidden_id").setAttribute("value","final submit");
form1.submit;
Now on my server, i checked for the value of this hidden field as :-
if(request.getParameter("hidden_id").equals("partial Submit"))
{
// make a database connection, pass the value user selected from the drop down box
// to a prepared statement that does the query for getting the 'productName' from
// the database, collect the returned string in a variable and set a
// request attribute with this returned value. This value can simply be used in the
// jsp to fill in the value part of the textbox1.
}
else
{
if(request.getParameter("hidden_id").equals("final Submit"))
{
// do the rest of the final processing that needs to be done when user finally
// submits the completed form.
}
else
{
// throw an exception to take care of the possibility that the user might send
// in a 3rd value as a value for the hidden field.
}
}
Since you havent provided the code for selectProduct(this.value) , i presume that it submits the jsp page as when you change the value in the drop down.
If that the case in the servelt, set the value that you want to show in jsp in request object
request.setAttribute("valuetodisplay" ,valuetodisplay);
and now in jsp
<input type="text" value ='<%= request.getAttribute("valuetodisplay")%>' />

Categories