I am creating a social networking site and I am facing one problem.
I am fetching records from database and with each record I want to add one button so that I can change that record using that text box.
But when I am updating record using that text box, it is getting value of the first text box only. If I am updating 2, 3, 4, 5 etc record then it is getting value of first text box.
So please help me how can I get value of each and every text box - not just from the first one.
Thanks in advance.
Below is my code:
<%
Statement st1;
ResultSet rs1;
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dfmc","root","93Pb3gaNv0");
String sql1="select * from user_table LIMIT 5";
st1 = con.createStatement();
rs1=st1.executeQuery(sql1);
String id=null,name=null;
while(rs1.next()){
id=rs1.getString("id");
name=rs1.getString("first_name");
%>
<div><input type="text" name="txt" id="name" />
<input type="button" name="btn" value="Rating" onclick="loadXMLDoc(<%=id%>)">
<p id="showname"><%=name%></p>
</div>
<script type="text/javascript">
function loadXMLDoc(iid){
var idd=iid;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("showname").innerHTML=xmlhttp.responseText;
}
}
var name;
name = document.getElementById("name").value;
xmlhttp.open("GET", 'insert_rating?name='+name+'&id='+idd+'', true);
xmlhttp.send();
}
</script>
I was also facing the same problem, but I could easily get javascript dynamic text box value on servlet, by using request.getParameterValues("DynamicTextBox");
client side code:
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
server side code (servlet):
String[] duration= request.getParameterValues("DynamicTextBox");
for (String string : duration) {
System.out.println("Duration1=="+string);
}
Related
Could you please help me in sorting this issue as im just learning ajax and trying to incorporate for my requirement.
My Requirement:
When i click a particular image it should call the same page but load with the table data with different values based on the param values called.So I was advised to go for AJAX as it doesnt reload the whole page .
JQUERY
$("#goToCostTypeID").click(function () {
var costType = document.getElementById("costType").value;
if(costType == "Actual"){
costType = "Budget";
document.getElementById("costType").value = "Budget";
} //if actuals ends
if(costType == "Budget"){
costType = "Forecast";
document.getElementById("costType").value = "Forecast";
} //if actuals ends
if(costType == "Forecast"){
costType = "Actual";
document.getElementById("costType").value = "Actual";
} //if actuals ends
var Budget = costType;
$.ajax({
dataType : "html",
url:'my.jsp?productID=6&appID=6&txtHidden=Costs&mode=Edit&costType='+costType,
type:'POST',
contentType :'application/x-www-form-urlencoded; charset=UTF-8',
data:{costType:Budget},
success:function(result){
console.log("YES");
$("#costContent").load('my.jsp?productID=6&appID=6&txtHidden=Costs&mode=Edit&costType='+costType);
}
});
});
HTML
<td width="2%" id="goToCostTypeID"> <a href="#" ><img src="../images/goto.png"/></a></td>
<div id="costContent">
<td width="13%" ><input type="hidden" id="cost_type_<%=i+1 %>" name="cost_type_<%=i+1 %>[]" value="<%=Bean.getLevelTwoOrgId()%>"/><%=Bean.getCcLevel2()%></td>
<td width="12%" ><input type="hidden" id="intival_<%=i+1 %>" name="intival_<%=i+1 %>[]" value="<%=Bean.getInitProj()%>"/><%=Bean.getInitProj()%></td>
JAVA
String costType = request.getParameter("costType");
uploadCostList =DAO.doGetAppCostUploadedList(PK_AppID,costType,iPresentYear);
Im getting the same table multiple time when I click the image. Please help me.
With Regards,
Saranya C
As far as I can understand your requirements you need simply to do smth like this:
$("#goToCostTypeID").on('click', function() {
const currentCostType = $('#cost_type').val();
const nextCostType = currentCostType === 'Actual' ? 'Budget' : currentCostType === 'Budget' ? 'Forecast' : 'Actual';
$('#cost_type').val(nextCostType)
const url = 'my.jsp?' + $.param({
productID: '68',
appID: '68',
txtHidden: 'Costs',
mode: 'Edit',
costType: $("#costType").val()
});
$("#costContent").load(url);
});
I have created a table to display data and there is a checkbox next to each of the data. I want to create a function where if the user click the checkbox of that data and press the delete button, the data will be remove from the table and the database. I have came up with the code but it doesn't remove the data. What is the problem with my code ?
Display on Webpage
HTML
<%
String id = request.getParameter("hiddenID");
String sql1="";
{
sql1 = "select * from exercise1";
PreparedStatement pstmt1=conn.prepareStatement(sql1);
ResultSet rs1 = pstmt1.executeQuery();
while(rs1.next()){
String arm = rs1.getString("Arm");
String time1 = rs1.getString("Time1");
out.println("<tr>");
out.println("<td style = 'width: 20%'>");
out.println(arm);
out.println("</td>");
out.println("<td style = 'width: 5%'>");
out.println(time1);
out.println("</td>");
%>
<td style="width: 5%"><input class="mychkbox" type="checkbox"
value="<%=id%>" form="multipleDele" name="DeleteChkbox" /></td>
<%
out.println("</tr>");
}
conn.close();
}
%>
This is my delete.jsp file
<%
String[] id = request.getParameterValues("DeleteChkbox");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (id != null)
{
for(int i=0;i<id.length;i++){
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(id[i]));
//pstmt.setInt(1, Integer.parseInt(id[i]));
int rec=pstmt.executeUpdate();
if (rec==1)
count++;
}
}
//System.out.println(functions);
%>
<form action="exercise.jsp" method="post">
<label><%=count%> record(s) deleted!!</label>
<input type="submit" value="Return" name="ReturnBtn" />
</form>
<%
conn.close();
} catch (Exception e) {
out.println(e);
}
%>
The id you are writing to the checkbox value is not coming from the database results. It is being retrieved in the JSP from a request parameter:
String id = request.getParameter("hiddenID");
... and then being written to every checkbox field:
<input class="mychkbox" type="checkbox" value="<%=id%>" form="multipleDele" name="DeleteChkbox" />
You aren't writing a different id for each checkbox.
As such, it probably is not the id of any of the database records, and therefore none of them are being deleted.
You should be reading the id of each record in your while loop when building the HTML.
I suspect you need something like this:
<input class="mychkbox" type="checkbox" value="<%=rs1.getString("id")%>" form="multipleDele" name="DeleteChkbox" />
Your image has three columns: arm exercises, number of times and action. The DeleteChkboox field will only tell you if the field is selected or not for a particular row. You need to get the ids that have been selected for deletion. Unchecked checkboxes will not show up in an array of checkboxes so your form has to take this into account. It needs to look something like
<form action = "...">
<input type="submit" value="delete">
<input type="submit" value="assign">
<table>
<c:forEach items="${ records }" var="r">
<tr>
<td>
${ r.exercise }
</td>
<td>
${ r.times }
</td>
<td>
<input type="checkbox" value="${ r.id }" name="userAction">
</td>
</tr>
</c:forEach>
</table>
</form>
Then you need to change your jsp so that you get the ids of the selected rows. Change the jsp part that iterates your ids to
<%
// get array of ids
String[] ids = request.getParameterValues("userAction");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (ids != null) {
for(int i=0; i < ids.length; i++) {
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(ids[i]));
int rec=pstmt.executeUpdate();
if (rec==1) {
count++;
}
}
}
}
%>
That aside, it's generally not the best of ideas to be running sql updates in jsps if you can help it. Consider moving this logic to a controller class and using the jsp layer for presentation only.
EDIT
As per your comment "it's not working", instead of looking at this particular problem (why doesn't the code you wrote remove the data) you have to look at the bigger picture: what is the problem you are trying to accomplish?
It looks something like this, in plain English:
Show a user a set of records
Allow the user to mark the records they'd like to delete (array of checkboxes); allow the user to submit this information (the record ids)
Process (delete) the submitted ids
Step 1
Iterate over a list of records in jsp, inside a <form> element
For each record, create a checkbox whose value is that record's id
Step 2
Add a delete button allowing the user to submit the form of ids
Step 3
Process the submitted information: get the list of ids submitted in the request, iterate over it and delete the records one by one
Which step are you stuck on?
I have done the entire coding but data isnot getting inserted in the database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/userinfo?user=root&password=admin");
Statement statement = connection.createStatement() ;
resultset = statement.executeQuery("select * from item") ;
Now this is the part where i have done the connection and i think it is okay because in first part where i display values from database it is working
Now that i have done this in the next part i have taken input values from input boxes
<input type="submit" value="RECEIVE" style="width:100px; height:40px"
name="receive ">
now <%
PrintWriter pw = response.getWriter();
PreparedStatement pst = null;
if(request.getParameter("receive")!=null)
{
String dob=request.getParameter("datepicker");
String supplier=request.getParameter("supplier");
String type=request.getParameter("type");
String quantity=request.getParameter("quantity");
String queryString = "INSERT INTO stock_quantity values(?,?,?,?)";
pst = connection.prepareStatement(queryString);
pst.setString(2,dob);
pst.setString(3,supplier);
pst.setString(4,type);
pst.setString(5,quantity);
int i = pst.executeUpdate();
if(i!=0){
%>
<script language="javascript">
alert("Send sucess");
</script>
<%
}
else{
%>
<script language="javascript">
alert("Enter all data");
</script>
<%
}
}
%>
The data doesnt gets inserted.. Find the problem in the code
Don't make connection with db in first controller(in your case in jsp), just send your data to another controller, and there you can insert it to db. You can use either #Requestparam("param") to get single parameters, or #ModelAttribute("name") to get entire POJO object(where you will have your all parameteres).
So your html file would look like (in thymeleaf) you need to change some of thymeleaf things to jsp:
<form action="#" th:action="#{/save}" th:object="${yourObject}" method="post">
<div>
<label for="quantity">quantity:</label>
<input type="quantity" th:field="*{quantity}">
</div>
<button type="submit">Submit</button>
</form>
And your second controller:
#PostMapping("save")
public String reset(#ModelAttribute(value = "yourObject") YourPOJOClass request) {
//save to DB
}
If you want to accept parameters, not entire object, add name parameter to jsp/html
for example:
<div>
<label for="quantity">quantity:</label>
<input type="quantity" th:field="*{quantity}" name="quantity">
</div>
And in controller you can get this parameter like that:
#PostMapping("save")
public String reset(#RequestParam("quantity") String quantity)
I am working on replacing a large dropdown ( which makes a performance impact due t browser rendering) with a Jquery autocomplete input box. I can get the autocomplete functionality to work however the selected value doesn't get available in the java bean class. Here is my code
<script>
var productionSourceListString = document.getElementById("hiddenField").value;
var productionSourceListArray = productionSourceListString.split(',');
$(document).ready(function(){
$("#centerForm\\:production_source").autocomplete({ source : productionSourceListArray, minLength: 3 });
$( "#centerForm\\:production_source" ).on( "autocompletechange", function() {$( "#centerForm\\:production_source" ).attr("value",this.value);} );
});
</script>
<h:inputText id="production_source" style="width:80px; overflow:hidden" value="#{recurringSplitBean.item.productionSource.description}">
</h:inputText>
<input type="hidden" id="hiddenField" value="#{productionSourceBean.productionSourceList}"/>
Production Source Spring Bean Class(To get the list of elements in dropdown and store them in a comma delimited string declared globally, which the Jquery accesses in the first code snippet)
private String productionSourceList = ""; (GLOBAL)
public void getProductionSourceListAjax(AjaxBehaviorEvent event){
List<String> localList = new ArrayList<String>();
Iterator<ProductionSource> iterator = this.getLovItems().iterator();
while(iterator.hasNext())
{
localList.add(iterator.next().getDescription());
}
productionSourceList = StringUtils.collectionToCommaDelimitedString(localList);
}
When I try to access the value in RecurringSplitBean class
if(AppSupport.isEmpty(item.getProductionSource()) || AppSupport.isEmpty(item.getProductionSource().getProductionSourceId())){
JsfMessage.addError("production_source","error.value.required");
return null;
}
item.getProductionSource().getDescription() is null. However rather than selecting a value from the list provided by the Jquery dropdown if I type a value in the input box the value becomes available in the recurringsplitbean class. Any thoughts ? :)
So I finally figured it out by myself.I am posting this answer in hope it helps someone else out.
<script>
var productionSourceListString = document.getElementById("hiddenField").value;
var productionSourceListArray = productionSourceListString.split(',\"*\",');
var b = JSON.parse(productionSourceListArray);
var data={"users" :b};
var finalData =$.map(data.users, function(item) {
return {
label:item.label,
value:item.value,
id: item.id
}
});
</script>
<h1>
<h:outputText value="#{msg['recurring_split']}" styleClass="home_message" />
</h1>
<fieldset>
<legend>Recurring Split</legend>
<h:panelGrid columns="4" cellpadding="2" style="width:500px;">
<h:outputLabel for="production_source" value="#{msg['production_source']}">
<h:outputText value="#{msg['edit_alert']}" escape="false" />
</h:outputLabel>
<h:inputText id="production_source" style="width:80px; overflow:hidden" value="#{recurringSplitBean.item.productionSource.productionSourceCode}">
</h:inputText>
<h:inputText id="production_source_description" style="width:180px ;background-color: #E5E5E5;" value="#{recurringSplitBean.item.productionSource.description}">
</h:inputText>
In a nutshell, the reason the value didn't become available in the bean was because a ajax call wasn't being triggered by the autocomplete function. Since I couldn't find a direct way to trigger from autocomplete script. I created the following hidden button with having the list of space separated ID's of elements that I wanted to become available in the bean:-
<h:commandButton id="renderProductionSource" value="renderProductionSource" style="display:none">
<f:ajax execute="production_source production_source_description production_source_id"></f:ajax>
</h:commandButton>
And in the autcomplete function, I execute the hiddenButton.click() function
$(document).ready(function(){
$("#centerForm\\:production_source").autocomplete({ source : finalData, minLength: 3, select: function(event, ui) {
event.preventDefault();
var label = ui.item.label;
var value=ui.item.value;
var id = ui.item.id;
$( "#centerForm\\:production_source" ).attr("value",label);
$( "#centerForm\\:production_source_description" ).attr("value",value);
$( "#centerForm\\:production_source_id" ).attr("value",id);
$("#centerForm\\:renderProductionSource").click();
} });
});
Please I need your help for how to make dependent Textbox on Dropdown value that come form database in Jsp. Below code work fine with one textbox.But i don't know how to make multiple dependent Textbox.So help me.
Thanks.
tender.jsp:
<%
Connection conn = null;
Statement st = null;
ResultSet rs = null;*
conn = JDBCConnectionUtil.getConnection();
if(conn != null)
{
try
{
String woodSQL = "select fsa_wood_type_master_wood_type, fsa_wood_type_master_wood_weight,fsa_wood_type_master_wood_length,fsa_wood_type_master_wood_width,fsa_wood_type_master_wood_standard_rate from fsa_wood_type_master";
st = conn.createStatement();
rs = st.executeQuery(woodSQL);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
%>
<td>
<select id="woodType" onchange="populateWoodId();">
<%while(rs.next()){ %>
<option value="<%=rs.getString(1) %>"><%=rs.getString(2) %></option>
<%} %>
</select>
<input id="woodHeight" type="text" value="" />
</td>
}
JavaScrip:
function populateWoodId(){
var selectBox = document.getElementById('woodType');
/* selected value of dropdown */
var woodHeight = selectBox.options[selectBox.selectedIndex].value;
/* selected value set to input field */
document.getElementById('woodHeight').value = woodHeight;
}
Change you option tag line like this :
<option value='<%=rs.getString(1)+"#"+rs.getString(2)+"#"+rs.getString(3)+"#"+rs.getString(4)+"#"+rs.getString(5) %>'><%=rs.getString(2) %></option>
and in your javascript do like this :
function populateWoodId(){
var selectBox = document.getElementById('woodType');
/* selected value of dropdown */
var woodProp = selectBox.options[selectBox.selectedIndex].value;
/* selected value set to input field */
var splitVal=woodProp.split("#",5);
document.getElementById('woodHeight').value = splitVal[0];
document.getElementById('woodHeight1').value = splitVal[1];
document.getElementById('woodHeight2').value = splitVal[2];
document.getElementById('woodHeight3').value = splitVal[3];
document.getElementById('woodHeight4').value = splitVal[4]; //five different textboxes
}