Getting value of radio button from dynamic form - html

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%>">

Related

Differentiate multiple input form inside forEach statement

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?

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>

How to call html form fields in vbscript dynamically in a loop

So I have an html form created in classic asp that has about 25 check boxes with different labels. The checkboxes are written to the page via a loop that grabs the label values from a table and each checkbox is named similarly ("decreason1","decreason2","decreason3",ect...) using a loop variable.
I use a vbscript at the end of the page to validate the data on the page before passing with a submit button. I need to make sure that at least one of the checkboxes is checked before submitting the form.
dim i, checkedvalue ;
checkedvalue = false
for i = 1 to 25
if document.rtftadd.decreason1.checked = true then
checkedvalue = true
end if
next
I need the "document.rtftadd.decreason1.checked" to change with the loop to decreason2, decreason3
I'm not sure how to go about doing that.
Any help would be greatly appreciated.
There are a few different ways to do this and if you are seeking a validation method prior to form submission then JavaScript may be a better solution.
However, in an effort to address your question using only ASP Server side code for VBScript and considering your question suggest that you do not care which box is selected nor how many are selected then the following code may be a working solution for you.
By looking at all of the elements sent via the form and checking if your form name (without number) exist then this same block of code will work even if you increase or decrease the number of check boxes you are validating for input.
<%#LANGUAGE="VBSCRIPT"%>
<%
dim checkedvalue
checkedvalue = false
if request("btn1") = "Submit" then
For each item in request.form
if instr(item,"decreason") > 0 then
checkedvalue = true
end if
next
response.write "Checked Value = " & checkedvalue & "<br><br>"
end if
%>
<html>
<head></head>
<body>
<form method="post" action="index.asp" name="rtftadd">
<input type="checkbox" name="decreason1"> Box 1<br>
<input type="checkbox" name="decreason2"> Box 2<br>
<input type="checkbox" name="decreason3"> Box 3<br>
<input type="checkbox" name="decreason4"> Box 4<br>
<input type="checkbox" name="decreason5"> Box 5<br>
<br>
<input type="submit" value="Submit" name="btn1">
</form>
</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++ %>

How to display checkbox results according to my database model?

I have two variables, one stores the chexboxes and the other stores the values checked, I found a problem to display the checkboxes and their values (checked, not checked) from the controller to the view.
I have this code on the controller
$scope.infoParticipant = functionThatGetsParticipants();
for (var i = 0; i < $scope.infoParticipant.length; i++) {
if ($scope.infoParticipant[i].ch_type == 'checkbox_multiple') {
var optionsString = $scope.infoParticipant[i].cf_multiple_optionsList;
$scope.infoParticipant[i].optionsTab = optionsString.split(";");
var optionsSelected = $scope.infoParticipant[i].v_value.split(";");
}
}
In the precedent code these should be the values
optionsString = "ch1;ch2;ch3";
$scope.infoParticipant[i].v_value = "ch1;ch2";
According to this the checkboxes :ch1 and ch2 will be checked on the next view :
<div ng-show="l.ch_type=='checkbox_multiple'">
<label >My checkboxes</span></label>
<div class="row" ng-repeat="k in l.optionsTab">
<div class=" col-md-2 modal_style_input">{{k}} </div>
<div class="col-md-2"><input type="checkbox" name="option" class="md-input" id="option {{k}}" class="wizard-icheck" value="{{k}}" icheck ng-model="" /></div>
<div class="col-md-8"></div>
</div>
</div>
My question is how to modify my controller and what to put on ng-model to have my correct chexboxes checked?
Thanks in advance.
In your case, one solution would be to use ngCheck directive in your check boxes.
<input type="checkbox" id="option {{k}}" value="{{k}}" ng-check="isOptionAvailable({{k}})" /></div>
And the isOptionAvailable(opt) is a javascript function that you add to the scope which returns true when k is present in $scope.infoParticipant[i].v_value.
EDIT: To answer your last comment, I created a plunker showing how it works