<html>
<head>
<title>HTML Checkbox</title>
</head>
<body>
enter code here
<h2> Pick your most favorite fruits: </h2>
<form name="fruitcheckbox" action="fruits.php" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btnsave">
</form>
Anyone can give me an idea how to validate this checkobox array.
if(isset($_POST['btnsave']))
{ $fruit = $_POST['fruit'];
$values = array();
foreach($chkbox as $selection )
{ if(in_array($selection, $fruit))
{ $values[ $selection ] = 1; }
else
{ $values[ $selection ] = 0; }
}
this is part of my code. I want to limit the checked checkbox to 5. Thanks. I need it badly :|
Try this. You can limit in javascript itself. So you can limit user in client side no need to go server side. It will limit you for 4 items. You can change the number in the script to increase the value
<script type="text/javascript">
function validateitem(){
var items = document.forms['fruitcheckbox'];
var inc = 0;
var i;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
inc++;
}
}
if(inc == 0) {
document.getElementById("limitmsg").innerHTML = 'Select atleast 1 item.';
return false;
} else if(inc>4){
document.getElementById("limitmsg").innerHTML = 'You can select only 4 items.';
return false;
}
}
</script>
<h2>Pick your most favorite fruits:</h2>
<form name="fruitcheckbox" action="fruits.php" method="POST"
onsubmit="return validateitem();">
<input type="checkbox" name="fruit[]" value="orange"> Orange <input
type="checkbox" name="fruit[]" value="apple"> Apple <input
type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit <input
type="checkbox" name="fruit[]" value="banana"> Banana <input
type="checkbox" name="fruit[]" value="watermelon"> Watermelon <br> <span
style="color: red" id="limitmsg"></span><input type="submit"
value="Save" name="btnsave">
</form>
Do you need something like this?
if (isset($_POST['btnsave'])) {
$fruits = $_POST['fruit'];
$count = count($fruits);
if ($count > 5) {
// Error; Only 5 checks allowed
} else {
// Save the data
}
}
When you submit fields with brackets like in your example. name="fruit[]" it will be an array when it is received in the backend in php.
You could then just use this:
if(isset($_POST['fruit']) && count($_POST['fruit']) > 5) {
// add your error message
} else {
// Everything is fine as long as you dont have to select atleast one of them
}
If my understanding is not wrong you have more then 5 checkboxes and you want user to restrict to check only 5 checkboxes.
If this is the case then below code might help you.
$("input[name='fruit[]']").change(function(e) {
if($('input[name="fruit[]"]:checked').length==5) {
$("input[name='fruit[]']:not(:checked)").attr("disabled", true);
} else {
$("input[name='fruit[]']:not(:checked)").attr("disabled", false);
}
});
Above code will allow you to check only 5 check boxes, whenever user check the 5th checkbox it will disable the remaining unchecked checkboxes. whenever user uncheck any of the 5 checkboxes then it will enable all the checkboxes.
Related
I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.
Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}
You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.
I am trying to implement an online service called CleanTalk which requires me to deploy scripts on my boss' website pages. CleanTalk prevents spambots from filling out website forms and email signup fields. I followed their instructions carefully but have been unsuccessful in getting it to work.
If I put the script before any HTML code, all the following html on the rest of the page doesn't get displayed. When I put the code at the end of the page, then I can see all the HTML, fill out the form and submit it, but nothing goes through. There are also no spambot blockings recorded in my CleanTalk account, even when I use their spam email tester in the form fields.
Here is the php code provided by CleanTalk:
<!--CLEANTALK SCRIPT-->
<?php
session_start();
require_once (dirname(__FILE__) . '../javajq/cleantalk.class.php');
// Take params from config
$config_url = 'http://moderate.cleantalk.org/api2.0/';
$auth_key = 'nere2usu5ehe'; // Set Cleantalk auth key
if (count($_POST)) {
$sender_nickname = 'John Dow';
if (isset($_POST['login']) && $_POST['login'] != '')
$sender_nickname = $_POST['login'];
$sender_email = 'stop_email#example.com';
if (isset($_POST['email']) && $_POST['email'] != '')
$sender_email = $_POST['email'];
$sender_ip = null;
if (isset($_SERVER['REMOTE_ADDR']))
$sender_ip = $_SERVER['REMOTE_ADDR'];
$js_on = 0;
if (isset($_POST['js_on']) && $_POST['js_on'] == date("Y"))
$js_on = 1;
$message = null;
if (isset($_POST['message']) && $_POST['message'] != '')
$message = $_POST['message'];
// The facility in which to store the query parameters
$ct_request = new CleantalkRequest();
$ct_request->auth_key = $auth_key;
$ct_request->agent = 'php-api';
$ct_request->sender_email = $sender_email;
$ct_request->sender_ip = $sender_ip;
$ct_request->sender_nickname = $sender_nickname;
$ct_request->js_on = $js_on;
$ct_request->message = $message;
$ct_request->submit_time = time() - (int) $_SESSION['ct_submit_time'];
//Additional parameters. You could the description at the bottom of the page.
$ct = new Cleantalk();
$ct->server_url = $config_url;
// Check
$ct_result = $ct->isAllowMessage($ct_request);
if ($ct_result->allow == 1) {
echo 'Message allowed. Reason ' . $ct_result->comment;
} else {
echo 'Message forbidden. Reason ' . $ct_result->comment;
}
echo '<br /><br />';
}
else
{
$_SESSION['ct_submit_time'] = time();
}
?>
<!--CLEANTALK SCRIPT-->
And here is my html form code with the CleanTalk code I am required to add to it:
<!--CONTACT FORM-->
<form action="form.php" method="post" name="contact form" style="padding-bottom: 55px;">
<br>
<input class="formstyle round bgcolor purpleb" style="width: 631px;" type="text" name='name' placeholder="Full Name" required><br>
<!-- ADDED value="" TO THE EMAIL SECTION.-->
<input class="formstyle round bgcolor purpleb" type="email" name='email' required placeholder="Email" value="" style="float: left; width: 295px; margin-right: 15px;">
<input class="formstyle round bgcolor purpleb" type="tel" name='tel' required placeholder="Phone" style="float: left; width: 295px;"> <br>
<textarea class="formstyle round bgcolor purpleb messagebox" type="text" name='message' required style="height: 160px;" placeholder="Message"></textarea><br>
<input type="checkbox" id="spambot" name="spambot" value="Yes" required> <label for='spambot'><span class="parastyle grey">Yes, I'm human</span></label>
<br /><br />
<!--For Cleantalk-->
<input type="hidden" name="js_on" id="js_on" value="0" />
<input type="submit" class="purpleb round formstyle bgcolor sendform" value="SEND" name='submit' style="float:left">
<label for='submit'><a class="reco grey" href="/privacy" target="_blank"><span style="text-decoration: none; display: inline-block;"> </span>PRIVACY POLICY</a></label>
<!--For Cleantalk-->
<script type="text/javascript">
var date = new Date();
document.getElementById("js_on").value = date.getFullYear();
</script>
</form>
<!--CONTACT FORM-->
Here is a link to the CleanTalk API installation instructions. If you need anything else just let me know.
Here are the error message I'm getting:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php:19) in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 72
Warning: require_once(/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php): failed to open stream: No such file or directory in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73
Fatal error: require_once(): Failed opening required '/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php' (include_path='.:/usr/local/lib/php-5.5.22-amd64/lib/php') in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73
I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>
I am new to programming and this problem is bothering me for 3 days straight...
I have a post form on .jsp site for gathering name, surname, mail,... and all this info is saved in object USER. I want to save users in array and display them on the same site. But everytime I use submit button in form new session is created and on array output info is only one user.
What should I do to solve this problem?
ps: on this stage i can't use sql because it's school projects
<% Uporabnik uporabnik = new Uporabnik(); //user
uporabnik.setIme(request.getParameter("ime"));
uporabnik.setPriimek(request.getParameter("priimek"));
uporabnik.setEmail(request.getParameter("email"));
uporabnik.setKraj(request.getParameter("kraj"));
uporabnik.setPostnaStevilka(request.getParameter("postnaStevilka"));
ArrayList<Uporabnik> seznamUporabnikov = new ArrayList<Uporabnik>(); //array with i want to display
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov); %>
<form method="post" action="Registracija.jsp">
Ime: <input type="text" name="ime"/> <br/>
Priimek: <input type="text" name="priimek"/> <br/>
Email: <input type="text" name="email"/> <br/>
Kraj: <input type="text" name="kraj"/> <br/>
Postna stevilka: <input type="text" name="postnaStevilka"/> <br/>
<input type="submit" name="potrdi" value="Vnesi">
<input type="reset" name="tabelaReset" value="Izbrisi iz tabele">
<input type="submit" name="resetiraj" value="Izbrisi podatke">
</form>
<br/> Seja: <%=session.getAttribute("Oseba")%> <hr/>
<% if (request.getParameter("potrdi")!=null) {
session.setAttribute("Oseba", uporabnik);
} %>
<% if (request.getParameter("resetiraj")!=null) {
session.setAttribute("Oseba", null);
} %>
change these lines:
...
ArrayList seznamUporabnikov = new ArrayList(); //array with i want to display
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
...
to
...
ArrayList seznamUporabnikov=session.getAttribute("seznamUporabnikov");
if(seznamUporabnikov == null) { //check if already in session before creating.
ArrayList seznamUporabnikov = new ArrayList(); //array with i want to display
}
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
...
create a class and create a static user list under that class and add all users in that list
this list will be available throughout your application lifecycle.
Okay after 4 days this stuff works now!!! I am so happy :) anyway.. thank you guys for getting me on the right track...
ArrayList<Uporabnik> seznamUporabnikov=null;
//check if already in session before creating.
if(session.getAttribute("seznamUporabnikov") == null) {
seznamUporabnikov = new ArrayList<Uporabnik>();
//array which I want to display
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
} else {
seznamUporabnikov =
(ArrayList<Uporabnik>)session.getAttribute("seznamUporabnikov");
}
if (request.getParameter("potrdi") != null) {
seznamUporabnikov.add(uporabnik);
}
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
I have several check box in a form I just wanna way to check whether they are checked or not .
If checked i need to store their id in the database(that i can do it ) . But my question is how to determine whether are checked or not instead of checking for each check box on at a time . I need to check whether its checked or not inside a servlet.
This is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Role Id<input type="text" name="roll_id"/><br>
Role Name<input type="text" name="roll_name"/><br>
Role Description<textarea name="roll_desc"></textarea><br>
<br>
<br>
Screen1<br>
tab1<br>
<input type="checkbox" name="s1_t1_view" value="s1_t1_view" >view<br>
<input type="checkbox" name="s1_t1_add" value="s1_t1_add" >add<br>
<input type="checkbox" name="s1_t1_edit" value="s1_t1_edit" >edit<br>
<input type="checkbox" name="s1_t1_delete" value="s1_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s1_t2_view" value="s1_t2_view" >view<br>
<input type="checkbox" name="s1_t2_add" value="s1_t2_add" >add<br>
<input type="checkbox" name="s1_t2_edit" value="s1_t2_edit" >edit<br>
<input type="checkbox" name="s1_t2_delete" value="s1_t2_delete" >delete<br>
Screen2<br>
tab1<br>
<input type="checkbox" name="s2_t1_view" value="s2_t1_view" >view<br>
<input type="checkbox" name="s2_t1_add" value="s2_t1_add" >add<br>
<input type="checkbox" name="s2_t1_edit" value="s2_t1_edit" >edit<br>
<input type="checkbox" name="s2_t1_delete" value="s2_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s2_t2_view" value="s2_t2_view" >view<br>
<input type="checkbox" name="s2_t2_add" value="s2_t2_add" >add<br>
<input type="checkbox" name="s2_t2_edit" value="s2_t2_edit" >edit<br>
<input type="checkbox" name="s2_t2_delete" value="s2_t2_delete" >delete<br>
<input type="submit" name="sumbit" text="submit">
</body>
</html>
But in my code I have several check boxes . I need to hardcode that for every check box . Is there way so that i put it in a loop and check for all check boxes ?
To be simple, you can use the name attribute to get the data since you are using different name for each checkbox.
In Servlet :
String[] s1_t1_view = request.getParameterValues("s1_t1_view");
String[] s1_t1_add = request.getParameterValues("s1_t1_add");
If you want to use group of checkbox to give the user a choice between multiple values, you will need to iterate over the group in the servlet. You can use this :
In HTML : (same name = same group)
<input type = "checkbox" name = "s1_t1" value = "s1_t2_view" >View <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_add" >Add <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_edit" >Edit <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_delete" >Delete<br>
In Servlet :
String[] results = request.getParameterValues("s1_t1");
for (int i = 0; i < results.length; i++) {
System.out.println(results[i]);
}
You can use
String[] checked = request.getParameterValues("checkboxName");
and then check the checked value
For me this one worked.
String[] selecttype=request.getParameterValues("selectType");
//selectType is the name of checkbox in jsp page.
This will return selected checkbox values.
Create hidden fields as
Now in your servlet as: String[] names = request.getParameterValues("checkbox");
PrintWriter pw = new PrintWriter(new File("/Desktop/sticker.txt"));
for(int i=0; i < names.length; i++) {
if(i + 1 < names.length && names[i].equals(names[i+1])) {
pw.write(names[i] + ",true\n");
++i;
} else {
pw.write(names[i]+",false\n");
}
}
pw.close();