I'm trying to make a validate form. I can't get my validate form to work properly the phone function is not working and I'm not sure if it's just submitting it even if the user press submit, could anyone help me?
html:
<form onsubmit="return validate();" name="formValidation">
<label>First Name:</label>
<input type="text" name="firstName" /><br /><br />
<label>Last Name:</label>
<input type="text" name="lastName" /><br /><br />
<label>E_mail:</label>
<input type="text" name="Email" onchange="validateEmail(this.value)"/><br /><br />
<label>Confirm E_mail:</label>
<input type="text" name="confirmEmail" onchange="validateEmail(this.value)"/><br /><br />
<label>Address:</label>
<input type="text" name="Address" /><br /><br />
<label>Telephone nr:</label>
<input type="text" name="fld" /><br /><br />
<br />
<p>submit your form: </p><input type="submit" value="Submit" />
</form>
js:
function validate(){
if(document.formValidation.firstName.value == "" ||
document.formValidation.lastName.value == "" ||
document.formValidation.Email.value == "" ||
document.formValidation.confirmEmail.value == "" ||
document.formValidation.Address.value == "" ||
document.formValidation.fld.value == "")
{
alert("Please fill all the boxes before submitting!");
return false;
} else if (telPhone(document.formValidation.fld.value)!=""){
alert(error)
return false
}else {
alert('Your form has been submitted!');
}
}
function validateEmail(Email)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(Email))
{
return true;
}
alert("You have entered an invalid email address!")
return (false)
}
function telPhone(fld) {
var error = "";
if (fld == "") {
error = "You didn't enter a phone number.";
} else if (isNaN(fld)) {
error = "The phone number contains illegal characters.";
} else if (fld.length != 10) {
error = "The phone number is the wrong length. Make sure you included an area code."
}
return error;
}
<form onsubmit="return validate();" name="formValidation" action="fileto redirect here" method="post">
Related
addition.jsp
<form action="addition.jsp">
First Number
<input type="text" name="fno">
<br>
<br>Second Number
<input type="text" name="sno">
<br>
<br>Result
<input type="text" value="<%=Integer.parseInt(request.getParameter(" fno "))+Integer.parseInt(request.getParameter("sno ")) %>">
<br>
<br>
<input type="submit" value="ADD">
</form>
I want to display result in thrid textbox named Result on click of submit button.. i tried this code but getting error ..is there something am i missing..kindly help?
request.getParameter(" fno ") is string not a number therefore it will be a wrong format.
<%
String integer = request.getParameter("fno");
String integer1 = request.getParameter("sno");
int x = integer != null ? Integer.parseInt(integer) : 0;
int y = integer1 != null ? Integer.parseInt(integer1) : 0;
int z=x+y;
%>
<input type="text" name="integer" value="<%=z%>"/>
It can be achieved by simple java script as follow:
<html>
<body>
<form action="addition.jsp">
First Number
<input type="text" name="fno" id="fno"/>
<br>
<br>Second Number
<input type="text" name="sno" id="sno"/>
<br>
<br>Result
<input type="text" id="result"/>
<br>
<br>
<input type="button" value="ADD" onClick="setAddition();"/>
</form>
<script>
function setAddition()
{
var fno=document.getElementById("fno").value;
var sno=document.getElementById("sno").value;
document.getElementById("result").value=parseInt(fno)+parseInt(sno);
}
</script>
</body>
</html>
So, I have two questions in my HTML code. After submitting the button, my code should display whether question # 1 and # 2 is correct right after the specified number. But the "msg" just prints on question # 1. How do I make the "msg" prints on both number? Any help would be greatly appreciated. Thankies!
<html>
<head>
<script>
function checkAnswers(){
var retval = false;
for(i=0;i<document.myForm.q.length;i++){
if(document.myForm.q[i].value == "yes" && document.myForm.q[i].checked == true){
retval = true;
}
}
if(retval== true){
document.getElementById("msg").innerHTML="Correct Answer!";
}
else if(retval == false){
document.getElementById("msg").innerHTML="Wrong Answer!";
}
}
</script>
</head>
<body>
<form action="#" onsubmit="return checkAnswers(this)" name="myForm">
<h1>QUESTIONS<h1>
<h3>Question No. 1.) </h3> What is the world's number 1 shampoo?<br />
<input name="one" type="radio" value="yes" id="q"/>A. Hi</br>
<input name="one" type="radio" value="no" id="q"/>B. Hello</br>
<input name="one" type="radio" value="no" id="q"/>C. Ahh</br>
<input name="one" type="radio" value="no" id="q" />D. Kitkat</br>
<span id="msg"></span>
<br />
<h3>Question No. 2.) </h3> What is the world's number 1 shampoo?<br />
<input name="two" type="radio" value="no" id="q"/>A. Hi</br>
<input name="two" type="radio" value="yes" id="q"/>B. Hello</br>
<input name="two" type="radio" value="no" id="q"/>C. Ahh</br>
<input name="two" type="radio" value="no" id="q" />D. Kitkat</br>
<span id="msg"></span>
<input type="submit" name='submit' value="Submit">
<br />
<span id="score"></span><br />
</form>
</body>
</html>
See this fiddle!
I changed your id="msg" to name="msg", look at the javascript below to see why! (And because it's not a good idea to have multiple element with the same id)
I removed id="q" because we can already get all radio without it !
<!-- No need to pass 'this' inside checkAnswers because we won't use it ! -->
<form action="#" onsubmit="return checkAnswers()" name="myForm">
<h1>QUESTIONS<h1>
<h3>Question No. 1.) </h3> What is the world's number 1 shampoo?<br />
<input name="one" type="radio" value="yes"/>A. Hi</br>
<input name="one" type="radio" value="no"/>B. Hello</br>
<input name="one" type="radio" value="no"/>C. Ahh</br>
<input name="one" type="radio" value="no"/>D. Kitkat</br>
<span name="msg"></span>
<br />
<h3>Question No. 2.) </h3> What is the world's number 1 shampoo?<br />
<input name="two" type="radio" value="no"/>A. Hi</br>
<input name="two" type="radio" value="yes"/>B. Hello</br>
<input name="two" type="radio" value="no"/>C. Ahh</br>
<input name="two" type="radio" value="no"/>D. Kitkat</br>
<span name="msg"></span>
<input type="submit" name='submit' value="Submit">
<br />
<span id="score"></span><br />
</form>
This is your js, We create a list of unique radio name, then check their value and show the result:
function checkAnswers() {
var retval;
//This gets all radio !
var listRadio = document.querySelectorAll('input[type="radio"]');
//We need to loop only each group, not every radio
//This array will hold all the unique names !
var listNameRadioGroup = new Array();
//We loop all radio, when the name is not in the array, we add it
for (var i = 0; i < listRadio.length; i++) {
if (listNameRadioGroup.indexOf(listRadio[i].name) === -1)
listNameRadioGroup.push(listRadio[i].name);
}
//Then we only need to loop this new array to test each group
for (i = 0; i < listNameRadioGroup.length; i++) {
//We can access the value of the radio with .value on the element
//listNameRadioGroup[i] will return the current name to test
if (document.myForm[listNameRadioGroup[i]].value == "yes") {
retval = true;
//because msg is now a name, we can use getElementsByName and they will be in order !
//So we set the value to correct
document.getElementsByName("msg")[i].innerHTML = "Correct Answer!";
}
else {
retval = false;
document.getElementsByName("msg")[i].innerHTML = "Wrong Answer!";
}
}
return retval;
}
// i've edited your code a little and here it is. In your code, if you have choose the correct answer, and you change it, the "msg" doesn't change. it remains as "Correct answer!" even though it is a wrong answer. But thanks for your help!
<html>
<head>
<script>
function checkAnswers(){
var retval = false;
var inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
var inputName = inputs[i].getAttribute('name');
var msg = document.getElementById('msg-' + inputName);
if(inputs[i].value == "yes" && inputs[i].checked == true){
msg.innerHTML = 'Correct Answer!';
}
else if(inputs[i].value == "yes" && inputs[i].checked != true){
msg.innerHTML = 'Wrong Answer!';
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return checkAnswers()">
<h1>QUESTIONS</h1>
<h3>Question No. 1.)</h3>What is the world's number 1 shampoo?
<br />
<input name="one" type="radio" value="yes" />A. Hi
<br />
<input name="one" type="radio" value="no" />B. Hello
<br />
<input name="one" type="radio" value="no" />C. Ahh
<br />
<input name="one" type="radio" value="no" />D. Kitkat
<br />
<span id="msg-one"></span>
<br />
<h3>Question No. 2.)</h3>What is the world's number 1 shampoo?
<br />
<input name="two" type="radio" value="no" />A. Hi
<br />
<input name="two" type="radio" value="yes" />B. Hello
<br />
<input name="two" type="radio" value="no" />C. Ahh
<br />
<input name="two" type="radio" value="no" />D. Kitkat
<br />
<span id="msg-two"></span>
<br/>
<input type="button" name='submit' value="Submit" />
</form>
</body>
</html>
In normal time you not put two time the same id but...your javascript/jquery need to look like that:
function checkAnswers(){
var retval = false;
for(i=0;i<document.myForm.q.length;i++){
if(document.myForm.q[i].value == "yes" && document.myForm.q[i].checked == true){
retval = true;
}
if(retval== true){
$("span[id=msg]")[i].innerHTML="Correct Answer!";
}
else if(retval == false){
$("span[id=msg]")[i].innerHTML="Wrong Answer!";
}
}
}
Because you need to loop all the msg span in your html and point at them.
When I click on the button will be equal to the amount of undefind while the amount is equal to 1
in jsp page :
<%
String err1 = (String) request.getAttribute("err2");
int code = 0;
if (err1 != null){
code = Integer.parseInt(err1);
System.out.println(" code " + code);
}
%>
<button type="button" id="btnok">ok</button>
<br />
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
<br />
in jquery code:
$(document).ready(function() {
$("#btnok").click(function(event) {
var xxx = $("#txtcode").val();
alert("xxx 1 test + " + xxx);
});
});
The most likely reason is that the condition:
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
is not being met and the input is not being inserted to the DOM. Reload the page and view the page source to see if the input is inserted.
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 have done the following coding
ContactUs.jsp
<form action="contact1.jsp" method="post" id="contact_form">
<div class="name">
<label for="name"></label> <input type="text" placeholder="My name is" name="name" id="name_input" required>
</div>
<div class="email">
<label for="email"></label> <input type="email"
placeholder="My e-mail is" name="email" id="email_input" required>
</div>
<div class="telephone">
<label for="name"></label>
<input type="text" placeholder="My number is" id="telephone_input" name="telephone" title="lenght of number should be 10 digits for valid number" pattern="[1-9]{1}[0-9]{9}" required/>
</div>
<div class="message">
<label for="message"></label>
<textarea name="message" placeholder="I'd like to chat about"
id="message_input" cols="30" rows="5" required></textarea>
</div>
<div class="submit">
<input type="submit" value="Send Message" id="form_button" />
</div>
</form>
the the code for contact1.jsp is
String name=request.getParameter("name");
String email=request.getParameter("email");
String telephone=request.getParameter("telephone");
String message=request.getParameter("message");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/cinushi_university", "CinthiyaSingh", "Cinthiya#098");
Statement st=con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into contact values('"+ name + "','"+ email + "','"+ telephone + "','"+ message + "');");
if (i > 0) {
request.getSession().setAttribute("Message", "Sent Successfully!");
request.getRequestDispatcher("ContactUs.jsp").forward(request, response);
}
else{
request.getSession().setAttribute("Message", "Incomplete Process!");
request.getRequestDispatcher("ContactUs.jsp").forward(request, response);
}
//close connection
%>
Once I add the data to the form and submit it, this works fine, however post that on the same page when I click refresh it resubmits the data, I want the data from previous submission to clear when I redirect the response even to same ContactUs.jsp , if it is possible please help.
you can use java script History.replaceState() function to fix this issue.
The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters.
Add this script in jsp page-
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Or,
Only insert data in table 'user' if submit data in not there. you have to check with unique column.