Differentiate multiple input form inside forEach statement - html

I have an array of String, the length is variable. I need to create for each String two buttons: buy and remove. They manage the quantity of the correspondent element. Like this:
Resoult.
I tried this, works but it's not clear.
String go = request.getParameter("go");
if ((go != null)){
String[] info = go.split(",");
int index = Integer.parseInt(info[1]);
if (info[0].equals("+")) {
++quantita[index];
} else {
--quantita[index];
}}
...
<c:forEach var="i" begin="0" end="${length-1}" >
<%
int i = (int) pageContext.getAttribute("i");
out.print(products[i] + " (" + quantita[i] +" in cart)");
%>
<input type=submit name="go" value="-,${i}"/>
<input type=submit name="go" value="+,${i}"/><br>
</c:forEach>

Use <button type="submit"> instead of <input type="submit">. This HTML element allows you to set content via children rather than via value attribute. This way you can simply use the name attribute to indicate the action and the value attribute to indicate the identifier.
<button type=submit name="decrease" value="${i}">-</button>
<button type=submit name="increase" value="${i}">+</button>
String decrease = request.getParameter("decrease");
String increase = request.getParameter("increase");
if (decrease != null) {
--quantity[Integer.parseInt(decrease)];
}
else if (increase != null) {
++quantity[Integer.parseInt(increase)];
}
Is that clearer?

Related

How to avoid null values from insertion into the database?

This question is related to this question.
I have created many input boxes using a for loop. from this whatever user type value, is get into another JSP page. from the input box values are getting properly.
But at the time of insertion that values into the database inserted as a blank or null. only if user type first input boxes in sequential order(first input box,second input box, third input box) then only value is getting inserted properly as per the expected results.
Even i'm checking the conditions also that is it contain null values or not. but still It'll will get inserted null values.
The main expected result is if user type particular value into the textbox then the value get inserted properly not the blank values get inserted into database.
<!-----new.jsp---------------------------------------------->
<%
for(int i = 0; i<ar.size(); i++)
{
%><span class="left-check"><%=ar.get(i)%></span><%
%>
<!--name=abc will be used in jsp to get value selected in checkboxes-->
<input id ="<%=idcounter%>" type="checkbox" name = "abc" value="<%=ar.get(i)%>" />
<input class = "left-marg-input7 size" id ="<%=idcounter%>" type="text" name = "abc_val" /><br><br>
<%
idcounter++;
}
%>
</center><br><br>
<center><button type= "submit" name="action" >SIGN UP</button></center>
</form>
</body>
</html>
Then the Next jsp page is :
<!------insertdata.jsp---------------------------------------------->
<html>
<%
String check[]= request.getParameterValues("abc");
String checkval[] = request.getParameterValues("abc_val");
String check_str = "";
String checkval_str = "";
if(check != null && checkval != null)
{
// there might be more one checkbox selected so, using loop
for(int i=0; i<check.length;i++)
{
// printing values selected from
check_str = check[i].toString();
checkval_str = checkval[i].toString();
if(checkval_str != null)
{
%><script>alert(<%=checkval_str%>);</script><%
st.executeUpdate("insert into user_assign_leave(org_email,user_email,leave_name,assign_leave,balance_leave)values('"+org_email+"','"+email+"','"+check_str+"','"+checkval_str+"','"+checkval_str+"')");
}
st.executeUpdate("insert into user_assign_leave(org_email,user_email,leave_name,assign_leave,balance_leave)values('"+org_email+"','"+email+"','"+check_str+"','"+checkval_str+"','"+checkval_str+"')");
}
}
st.executeUpdate("insert into user(org_name,org_email,name,email,mobile,custom_ID,pass)values('"+org_name+"','"+org_email+"','"+username+"','"+email+"','"+contactno+"','"+customer_id+"','"+password+"')");
%>
</body>
</html>

Unable to fetch the data of a column with radio buttons in jsp using servlet with request.getParameterValues() function

I have a table with 3 columns.Last column has 4 radio buttons in each row.I am not able to fetch all the values of radio buttons checked after submitting the form.I always get only one value which is the value of radio button checked in the first row.
Here is the code of jsp page:
<form action = "SaveData" method = "POST" target = "_blank">
<h1>LIST</h1>
<%
try {
/* Create string of connection url within specified format with machine
name, port number and database name. Here machine name id localhost and
database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/sample";
// declare a connection by using Connection interface
Connection connection = null;
/* declare object of Statement interface that is used for executing sql
statements. */
Statement statement = null;
// declare a resultset that uses as a table for output data from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters
of string type connection url, user name and password to connect to database.*/
connection = DriverManager.getConnection(connectionURL, "root", "password");
/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from data";
rs = statement.executeQuery(QueryString);
%>
<table class="comparison-table">
<tr>
<th>LIST</th>
<th>Y/N</th>
<th>OPTIONS</th>
</tr>
<div>
<tr>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<form>
<input type="radio" name="option" value="a" checked> A
<input type="radio" name="option" value="b" >B
<input type="radio" name="option" value="c" > C
<input type="radio" name="option" value="d"> D
</form>
</td>
</tr>
</div>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
}
catch (Exception ex) {
%>
<%
out.println("Unable to connect to database."+ex);
}
%>
</table>
<button value="Submit" id="button">Submit</button>
</form>
Here is the Servlet code:
import javax.servlet.annotation.WebServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
//Extend HttpServlet class
#WebServlet("/SaveData")
public class SaveData extends HttpServlet {
// Method to handle GET method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"+
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
}
Output after submitting the form would be values of two parameters "choose" and "option". I get proper output for "choose" parameter ie. all the selected Yes/No options in a cloumn,whereas for "option" parameter i would get only the value of first row selected radio button ie if i select 'c' in the first row radio buttons only 'c' will be displayed with rest of the rows ignored.
Please help me out in fetching data of all the columns of the radio buttons selected in a String array.
I also want to fetch the value of "slist" which is from database using servlet. This is under td tag with name="list".
First you sould not nest form tag, remove the form tag before radio button.
From MDN web docs :
elements of type radio are generally used in radio
groups—collections of radio buttons describing a set of related
options. Only one radio button in a given group can be selected at the
same time.
You should add a variable to differentiate lines like this for example :
<tr>
<%! int lineNumber = 0 %>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<input type="radio" name="option<%= lineNumber %>" value="a" checked> A
<input type="radio" name="option<%= lineNumber %>" value="b" >B
<input type="radio" name="option<%= lineNumber %>" value="c" > C
<input type="radio" name="option<%= lineNumber %>" value="d"> D
</td>
</tr>
<% lineNumber++ %>

Getting value of radio button from dynamic form

I have a form within a JSP that contains a multiple choice quiz, each question is followed by a group of radio buttons with the options, these are pulled from the database as questions don't all have the same number of options and the radio buttons are added as the form is created, each radio button has a label which contains the text answer. When submitting the page it is passed to another JSP, here I want to get the text from the label to store so I can check the answers.
here's the form, so each group of radio buttons is given the name based on question number, and each member of the group is given a id based on its question number and option within the question.
<form class="container" id="quiz" method="post" action="/quizChecker.jsp">
<% for (int i = 0; i < ques_nos.size(); i++) {
String query = "SELECT answer_text, is_correct FROM Quiz_Question_Option WHERE quiz_ques_id = ?";
PreparedStatement prepstmt = con.prepareStatement(query);
prepstmt.setInt(1, ques_nos.get(i));
ResultSet rsq = prepstmt.executeQuery();
rsq.last();
int size = rsq.getRow();
rsq.first();
%>
<p id="ques" class="Question"<%=i%>"><%=questions.get(i)%></p><br>
<% for (int j = 0; j < size; j++) {
%>
<input class="checkmark" type="radio" name="q<%=i%>" id="q<%=i%><%=j%>">
<label for="q<%=i%><%=j%>"><%=rsq.getString(1)%></label><br>
<% rsq.next();
}
}
session.setAttribute("ques", ques_nos);
%>
<button type="submit" value="checkQuiz">Submit Quiz</button>
</form>
Here's the code where I was trying to get the text value of the selected button.
<%
ArrayList<String> answers = new ArrayList<~>(5);
for (int i = 0; i < 5; i++) {
String given = request.getParameter("q"+i);
answers.add(given);
}
...
When I added a loop to print out what had been added to answers it returned "ononononon" so I guess I am accessing if the button is selected, as I would only be looking at selected radio buttons here, how do I get the value of the label instead?
Try setting a value for all the radio buttons
<input class="checkmark" value="answer1" type="radio" name="q<%=i%>" id="q<%=i%><%=j%>">
<input class="checkmark" value="answer2" type="radio" name="q<%=i%>" id="q<%=i%><%=j%>">

How to bind data from datepicker to a regular ng-model

jsp page:
<label>Script ID:</label>
<input name="scriptId" type="text"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}"
/>
<form>
<h1>Date Pannel</h1>
<fieldset>
Pick a start date:<br>
<input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerStart" ng-model="parent.startDate" onchange="document.getElementById('datePickerEnd').setAttribute('min', document.getElementById('datePickerStart').value)"><br><br>
Pick an end date:<br>
<input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerEnd" ng-model="parent.endDate" ><br><br>
<button ng-disabled = "mode =='BROWSE'" ng-click="setDates()"
>Set Dates</button>
</fieldset>
</form>
controller.js
$scope.parent = {startDate:''};
$scope.parent = {endDate:''};
$scope.selectedScript.startDate = null;
$scope.selectedScript.endDate = null;
$scope.setDates = function setDates() {
$scope.selectedScript.startDate = $scope.parent.startDate.getTime();
$scope.selectedScript.endDate = $scope.parent.endDate.getTime();
myAppFactory.setDates($scope.selectedScript.startDate, $scope.selectedScript.endDate, $scope.selectedScript.src).success(function(data) {
$scope.selectedScript.src=data;
});
}
That's all the code i need to get some stuff done...
Now I have a table on my jsp page...
<tr
ng-repeat="s in scripts
ng-click="selectScript(s, $index)"
ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
controller.js
$scope.selectScript = function(script, index) {
if ($scope.mode != 'BROWSE')
return;
$scope.parent.startDate = $scope.selectedScript.startDate; <-- this part
$scope.parent.endDate.setTime = $scope.selectedScript.endDate; <--and this
$scope.selectedScript = script;
$scope.selectedRow = index;
};
When I save the script, the data in the database has startDate and endDate
that works...
My problem is that selectedScript as a model, in the code above, don't has any value in startDate and endDate...it's null (but the fields exist, and the database has the data I need)
But I need somehow to make it possible that parent.startDate and endDate are bound to the selectedScript's startDate and endDate...
Btw, i 1st tried to make the ng-model of the datepicker like selectedScript.startDate, but that didn't work...
Later I found out that the datepicker has it's own scope, and that's causing my problems...at least I believe so.
I just hope that I have made myself clear...
Can you help me?
I think your issue is because when you retrieve the data from the database, it passes it as a string, which isn't a format that the datepicker can read.
Essentially what you need to do is parse it as a Date attribute, to do this you can do;
$scope.parent.startDate = new Date($scope.selectedScript.startDate);
$scope.parent.endDate = new Date($scope.selectedScript.endDate);
Use this in the relevant places to parse as a date, or you can set up a watch to do it for you whenever the value is changed;
$scope.$watch('parent.startDate', function(startDate){
$scope.parent.startDate = new Date($scope.parent.startDate);
});
You can only use $watch for single values, or you can watch the whole object as 'parent'.
Hope it helps!

How to make Razor not display special characters as html

The page I'm working on displays content from a database in readonly input box. My problem is that it's displaying any special characters as the html code (ie: & displays as &). How do you get the code to display properly?
I'm using QuerySingle to connect to the database, don't know if that makes a difference. I'm new to using Razor. Any help is much appreciated.
Code in question:
var queryloan = "SELECT * FROM loans WHERE LoanId = #0";
var queryloandata = db.QuerySingle(queryloan, queryformstatus_submitted.doc_loanid);
<form class="jotform-form" action="submit-form.cshtml?isadmin=#(isadmin)&loanid=#(loanid)" method="post" name="form_30905105572145" id="30905105572145" accept-charset="utf-8">
<input type="hidden" name="formID" value="30905105572145" />
<input type="hidden" name="doc_id" value="#doc_id" />
<div class="form-all">
<ul class="form-section">
<li id="cid_3" class="form-input-wide">
<div class="form-header-group">
<h2 id="header_3" class="form-header">
Borrower Sources & Uses Summary
</h2>
#if (queryformstatus_submitted.doc_approval == "Pending Approval" || queryformstatus_submitted.doc_approval == "Approved")
{
<text><br />
<br />
<div class="error">
This form has already been submitted and cannot be edited. It is for reference only.</div></text>
}
#if(userid != queryformstatus_submitted.doc_userid){
<text><br/><br/><div class="error">You may not edit this form. It is for reference only.</div></text>
}
</div>
</li>
<li class="form-line" id="id_4">
<label class="form-label-left" id="label_4" for="input_4">
1. Property Name:
</label>
<div id="cid_4" class="form-input">
<input type="text" class=" form-textbox" id="input_4" name="q4_1Property" size="40" value="#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)"/>
</div>
</li>
I'm not sure but I believe it may be something in this helper function that's causing the html code:
#helper checkEmptyPreFill(IEnumerable<dynamic> queryinputvalue, string field_id, string defaultval, int cloned = 0) {
var reqValue = queryinputvalue.FirstOrDefault(r => r.field_name.Equals(field_id));
var return_value = "";
if(reqValue != null){
return_value = reqValue.field_data;
} else {
return_value = defaultval;
}
if(cloned == 1){
return_value = "";
}
#return_value
}
The razor helper returns a HelperResult object so you'll have to convert it to a string before you can call HtmlDecode on it. Replace:
#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)
with the following:
#HttpUtility.HtmlDecode(Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName).ToString())
I would also suggest that you move some of the logic and data access code out of your view and into a controller but this should give you the result that you'e after.