Clear out an error message instead of appending with javascript - javascript

In this HTML form that I have I would like to warn the user that he has to enter a level in the inputbox, if he clicks the button again I would like to clear off the error message and print it out again. I would like to also add more error messages but anything that I add as an error message appends to the end of the previous message.
function validateForm () {
var msg = ""
, result = true;
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
here's a jsbin

function validateForm () {
var result = true;
if (document.ExamEntry.name.value === "") {
document.getElementById('name-msg').innerHTML= "You Must Indicate Your Level";
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>

Is this what are you looking for?
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value===""){
msg = document.createTextNode("You Must Indicate Your Level");
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild(msg)
document.getElementById('name-msg').style.color="red";
} else {
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"> </span>
<input type="submit" name="submit" value="Submit" onclick="validateForm();" />
</form>

You can clear the html like
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color = "red";
} else {
document.getElementById('name-msg').innerHTML = '';
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();" />
</form>

You may possibly use innerHTML:
function validateForm() {
var msg = "",
result = true;
if (document.ExamEntry.name.value === "") {
msg = "You Must Indicate Your Level";
}
document.getElementById('name-msg').innerHTML = msg;
}
#name-msg {
color: red;
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<br/>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>

Related

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

How to get value result from the same form?

How can I take value results from this form?
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
And, JS is:
function sakupiPodatke(form){
var delovi = [];
var elementi = form.elements;
for(var i=0; i<elementi.length; i++){
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
var teloZahteva = sakupiPodatke(document.forma);
console.log(teloZahteva);
also Php file is simple:
<?php
$ime = $_POST["txtIme"];
$email = $_POST["txtEmail"];
?>
so...my question is how to read variable "teloZahteva" from JS in console.log?
Your code is running when the page first loads, before the user has had a chance to fill in the form. So it will display empty values in the console.
Put the code in an event listener that runs when the user clicks the submit button.
document.getElementById("dunja").addEventListener("submit", function(e) {
e.preventDefault();
var teloZahteva = sakupiPodatke(e.target);
console.log(teloZahteva);
});
function sakupiPodatke(form) {
var delovi = [];
var elementi = form.elements;
for (var i = 0; i < elementi.length; i++) {
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
<form name="forma" method="post" action="index.php" id="dunja">
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
This displays the form values in the console instead of sending the form to PHP.
After my code I wrote this code and it says:
Uncaught ReferenceError: createXHR is not defined
function formPost(url, form, callback){
var xhr = createXHR();
var data = sakupiPodatke(form);
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 304){
callback(xhr.responseText);
}else{
alert("Greskica!");
}
}
};
xhr.send(data);;
}
function procesOdgovora(odgovor){
alert(odgovor);
}
formPost("index.php", document.forma, procesOdgovora);
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" onclick="handleSubmit()" />
</p>
</form>
handleSubmit(){
var ime =getElementById('ime').value;
var mail =getElementById('mail').value;
}

javascript form validation issue

for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">
You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>
try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'
I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">
function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}

Validation With Java Script and printing

I have a form in HTML and that if the fields are left blank, the Javascript will print inside the fields error. Please can some one give me a piece of code that will validate the form and then will print Error on top of the form if its left blank and not inside the fields of the form?
My Form:
<form id="contact" onsubmit="checkContactForm(); return false;" onreset="resetForm();">
<p>Fill in the form below to send me a message!</p>
<div id="errormessage"></div>
<p>
<label for=""> </label>
<input type="text" name="" id="" onfocus="" />
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" onfocus="resetField(this);" />
</p>
<p>
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" onfocus="resetField(this);" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" rows="5" cols="25" onfocus="resetField(this);"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
My Javascript:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
}
}
if (!emptyFields) { myForm.submit(); }
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
Since HTML5 there is a form-validation API (http://www.w3schools.com/js/js_form_validation.asp)
Here you can find a pretty good "tutorial": http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/
If I've understand you want the error will be printed in the #errormessage div, right?
If so you can simply do something like this:
function addError(str){
document.getElementById("errormessage").innnerHTML = document.getElementById("errormessage").innerHTML + str + "<br>";
}
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
addError(fiedlName+" is empty!");
}
}
if (!emptyFields) { myForm.submit(); }
}

Categories