Populate textbox with info from combobox - java

I need to create a jsp page to edit data from an oracle database.
I thought that the easiest thing I could do was to create a combobox showing important info
(in this case: id+ name of the material) but I have problems filling the text fields.
My idea is to fill those fields after the text on the combobox changes, but I don't really know how to do it. I know that with the info of the combobox, I have to do a query to obtain the data and then recall the jsp or something, but I don't exactly if I have to call a Servlet or what is the best way to do it.
Sorry if this question is repeated, but I didn't find any posts helpful.
Some code:
<sql:setDataSource dataSource="bd/login"/>
<sql:transaction>
<%--Vamos a hacer una consulta a la bd--%>
<sql:query var="resultado">
select * from material order by codigo
</sql:query>
</sql:transaction>
<form name="formActualizar" action="../ServletActualizarDatos" method="POST">
<select name="select" styleId = "tempId" onchange="ActualizarDatos()">
<option selected="selected"> -- Elija material --</option>
<c:forEach var="material" items="${resultado.rows}">
<option value="${material.codigo}">${material.codigo} ${material.nombre}</option>
</c:forEach>
</select><br/><br/>
Código<br/>
<input type="text" name="codigo" value="" /></p>
Nombre<br/>
<input type="text" name="nombre" value=""/></p>
Resistencia<br/>
<input type="text" name="resistencia" value="" /></p>
<input type="submit" name="bt" value="Actualizar Material" />
</form>
<script>
function ActualizarDatos()
{
String texto = this.options[this.selectedIndex].text;
Material m = ServletActualizarDatos.ObtainMaterialFromCombo(text);
this.form['codigo'].value=String.valueOf(m.getCodigo());
this.form['nombre'].value=m.getNombre();
this.form['resistencia'].value=String.valueOf(m.getResistencia());
}
</script>
Thank you for your help.
///CODE UPDATED, DOESN'T SEEMS TO WORK YET, THE EVENT IS NOT CALLED

You need jvascript to handle event when select box change to set the values of input fields from this select box selected value and selected option.
<select name="select" styleId = "tempId" onchange="this.form['codigo'].value=this.value;this.form['nombre'].value=this.options[this.selectedIndex].text;">

Related

Spring boot [Thymeleaf]: EL1008E: Property or field 'category' cannot be found on object of type 'java.util.Optional'

I have a relationship between two tables product and product category. Now i want to Edit product.
I created a list, which when i click edit open another interface with product details plus Product category as an drop down, but i get an error on thymeleaf th:selected as i want it to display the drop down with the selected item in it, but i get error
EL1008E: Property or field 'category' cannot be found on object of type 'java.util.Optional'
Please help to resolve
I tried to change the select to input it works fine
<input type="text" class="form-control" id="name" name="name" th:field="<b>${update.category.ProductCategoryID}"</b> />
but using selected dont work
<select class="form-control" id="category" name="category">
<option
th:each="prodCat : ${prodCatList}"
th:value="${prodCat.ProductCategoryID}"
th:text="${prodCat.CategoryName}"
th:selected="${prodCat.ProductCategoryID} =={update.category.ProductCategoryID}">
</option>
</select>
Below is the code snip
<form th:object="${update}" th:action="#{/product/save}" method="post">
<div id="myForm">
....
<input type="text" class="form-control" id="name" name="name" th:field="${update.category.ProductCategoryID}" />
<select class="form-control" id="category" name="category">
<option
th:each="prodCat : ${prodCatList}"
th:value="${prodCat.ProductCategoryID}"
th:text="${prodCat.CategoryName}"
th:selected="${prodCat.ProductCategoryID} == ${update.category.ProductCategoryID}" <-- problem
>
</option>
</select>
<input type="text" class="form-control" id="ProdID" name="ProdID" th:field="${update.category.CategoryName}" />
It seems that Update is Optional and not an object, and the view received the Öptional rather than Update directly.
//something like this needs to be done when updating the model for this attribute
Optional<Update> update = <your code to get this in Java>
update.ifPresent(foundUpdateObject -> model.addAttribute("update", foundUpdateObject))
Thanks TechFree.
It work, I was doing a mistake where I am not taking the object from the Optional Class
Here is the code i put and it worked.
#GetMapping("/edit/{pctid}")
public String findOne(
#PathVariable(value = "pctid") Integer pctid,
Model model) {
model.addAttribute("prodCatList", productCategoryRepo.findAll());
productRepo.findById(pctid).ifPresent(o -> model.addAttribute("update", o));
// model.addAttribute("update",productRepo.findById(pctid));
return "/prod/edit";
}

Adding button and textbox dynamically in jsp page

<form:form action="approveAccount.html" method="GET">
<input type="submit" value="approvAll"/>
<p>Following Accounts are Pending to approve</p>
<c:forEach items="${accountIdList}" var="val">
<li>${val}</li>
</c:forEach>
</form:form>
val is the value that is fetched from database, I want to add a submit button and want to use this fetched value to do some stuffs, how many value get fetched is dynamically decided, how todo that.. here in this scenario, I am getting account id which admin needs to approv, so by adding textbox, admin can assign the role to the this account and then submit the to the database and this all happen with that clk of button
Suppose, in your service class, you have list of accountIds like this
ArrayList<Integer> accountIdList = new ArrayList<>();
accountIdList.add(1);
accountIdList.add(2);
accountIdList.add(3);
& you have added this list into HTTP Session object for further use like
session.setAttribute("accountIds",accountIdList);
In your JSP, you can then use JSTL for-each loop to create dynamic buttons & textboxes as below
<c:forEach var="ids" items="${session.accountIds}" varStatus="loop">
<input type="text" name="role${loop.index}" />
<input type="submit" value="<c:out value=${ids} />" />
</c:forEach>
I hope this helps.
If I understood your question right, your trying to get multiple ids and it's associated roles when the user click submit button. You can try the following to get them:
JSP:
<form:form action="approveAccount.html" method="GET">
<input type="submit" value="approvAll"/>
<p>Following Accounts are Pending to approve</p>
<c:forEach items="${accountIdList}" var="val">
<input type="text" value="${val}" name="id">
<select name="role">
<option value="admin">Admin</option>
<option value="user">user</option>
</select>
</c:forEach>
</form:form>
Servlet:
String [] txt = request.getParameterValues("id");
String [] role = request.getParameterValues("role");
for (int i = 0; i < txt.length; i++){
System.out.println(txt[i]+" "+role[i]);
}

How to retrive data from DB for a selected dropdown value using only JSTL?

guys i am working on web application in jsp and servlets .. in myjsp.jsp i have a list
List<String> sexList = (List<String>)request.getAttribute("sexList"); %>
and put it in cumbo box in html tag like this
<td>Gender:</td>
<td><select name="sex">
<%for(String i : sexList) { %>
<option value="<%=i%>"><%=i %></option><%}%>
</select>
</td>
but now i want to select the selected item from database using JSTL and i want to know how to return or get this selected item .. any help
You need to include it in the form and post it to servlet:
selection.jsp:
<form action="display.jsp" method="GET">
<select name="sex">
<c:forEach items="${sexList}" var="sex">
<option value="${sex}">${sex}</option>
</c:forEach>
</select>
<input type="submit" value="submit"/>
</form>
display.jsp
<c:set var="sex" value="${param.sex}" scope="page" /> //Gets the selected sex
<sql:query var="person" >
select * from Person where sex = ?
<sql:param value="${sex}" />
</sql:query>

HTML Select box returning null in Servlet

I have an HTML form that looks like this:
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" size="50" />
<input type="submit" value="Upload File" />
<select name="options">
<option value="public">Public File</option>
<option value="locker">Locker File</option>
</select>
</form>
I want the user to select a file and then select an option from the dropdown to choose where the file is saved to.
I am attempting to retrieve the value of the option using
String option = request.getParameter("options");
However, for some reason, the option is null, despite choosing an option.
Anyone know why this is?
I found the solution after tearing through results on StackOverflow/Google.
The issue comes into play with the "multipart/form-data" enctype attribute on the form element. Whenever you call .getParameter with that enctype, it will return null.
For a solution, check out this question/answer

How to get the value of drop down list?

I want to get the value to of drop down list, to send back to server to match something.
Update:
Sorry, i has to be clear on my question. I am using javascript to get values in client side and sending those back to server with DWR & processing them with JAVA code.
<select><option selected="selected" value="1">EEE</option><option value="2">ECE</option><option value="3">IT</option><option value="4">CSE</option><option value="5">MECH</option></select>
'
<input id="id" type="text" size="5"/>
<input id="name" type="text" size="15"/>
<input id="age" type="text" size="5"/>
<input id="age" type="text" size="5"/>
'
I want to get the values(1,2,3,4,5) ALONG with the other Name, Id, Age values.
I can get field text using dwr.util.getValues().
How can I get that select option value?
Since you specify no server-side language, I assume you want in HTML/JS. So, use this code in javascript, assuming the ID of your combobox is combo1:
<script type="text/javascript">
var combo1 = document.getElementById("combo1");
var val = combo1.options[combo1.selectedIndex].text;
//this will show the value in a Dialog Box
alert(val);
</script>
<select id="id"> ...
var opts = dwr.util.byId("id").options;
Try giving your select element a name attribute:
<select name='department'>...

Categories