Form submission cancel using javascript not working - javascript

OBJECTIVE:
I have made a form containing 3 fields, I want that If there's even a single empty field left in form
the form , it is recognised and an error message(for each empty field) is printed (not alerted), and form submission is cancelled. The error msg is initially hidden and it should be made visible only when a field is left empty.
PROBLEM:
the code to stop submission is not working.
Please post any error. It works if use only alert(), and remove the code to show and delete hidden validaeFormOnSubmit() and validateEmpty().
FORM:
<form action="start.php" method="post" onsubmit="return validateFormOnSubmit(this)" >
<table>
<tbody>
<tr>
<td><label for="fname">Team Name:</label><br></td>
<td><input name="fname" type="text" autocomplete="off">&nbsp <div id="1"> Field is
required
</div></td>
</tr>
<tr>
<td><label for="contact">Contact 1 :</label> </td>
<td><input type="text" maxlength = "10" name="contact" > &nbsp<div id="2"> Field
is required </div></td>
</tr>
<tr>
<td><label for="contact2">Contact 2:</label> </td>
<td><input type="text" maxlength = "10" name="contact2" >&nbsp <div id="3"> Field is
required </div></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</tbody>
</table>
</form>
SCRIPT
<script >
$(document).ready(function () {
var i;
for(i=1;i<=3;i++)
{
var k='#'+i;
$(k).hide();}
});
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty(theForm.fname,1);
reason += validateEmpty(theForm.contact,2);
reason += validateEmpty(theForm.contact2,3);
if (reason != "") {
return false;
}
return true;
}
function validateEmpty(fld,k) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "error";
var k='#'+i;
$(k).show();
} else {
fld.style.background = 'White';
var k='#'+i;
$(k).hide();
}
return error;
}
</script>

I would suggest the following:
Remove the onsubmit="..." from your HTML
Bind to the onsubmit event programmatically:
$(...).on("submit", validateFormOnSubmit);
Change the signature of validateFormOnSubmit accordingly:
function validateFormOnSubmit(event) {
// use this instead of theForm
}
Instead of returning false do event.preventDefault(), i.e.:
if (reason != "") {
event.preventDefault();
}

What about this ?
http://jsfiddle.net/45Kfy/
<code>
$(document).ready(function () {
$("input").each(function(index, item)
{
if ($(item).val().length == 0)
{
$(item).css("background-color", "red");
}
});
});
</code>
Instead of documentReady() you should trigger the button click.
(jQuery get the input value in an .each loop)
And watch out, your button is an inputfield too.

Related

jQuery: Script isn't preventing submit function from firing when form has errors

Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

Display fields when user selects particular value from combo box - Validation logic issue

I have a combo box, and there are 2 values to be selected from it. either Male or Female. When user selects Male then another 2 textboxes gets displayed. Those 2 text box cann't be empty (as they are being validated).
The problem : When the user selects Female, the 2 textboxes discussed above is hidden, and I am not allowed to navigate to the next screen without filling some values to those 2 fields (because its being validated). How can i solve this?
My COde
<table>
<tr>
<td align="left">
<select id="gender" name="gender" onchange='genderfind(this.value);'>
<option value="female">female</option>
<option value="male">Male</option>
</select>
</td>
<td id="gb" style="display:none;"> <td>
<input type="text" name="name" /></td>
<td align="left"><span id="msg_name"></span> </td>
<td>
<input type="text" name="lastname" /></td>
<td align="left"><span id="msg_lastname"></span> </td>
</td>
</tr>
</table>
</body>
JQUERY
function validateStep() {
var isValid = true;
var un = $('#name').val();
if (!un && un.length <= 0) {
isValid = false;
$('#msg_name').html('first name missing').show();
} else {
$('#msg_name').html('').hide();
}
// validate password
var l = $('#lastname').val();
if (!l && l.length <= 0) {
isValid = false;
$('#msg_lastname').html('last name missing').show();
} else {
$('#msg_lastname').html('').hide();
}
return isValid;
}
///
<script>
function genderfind(val) {
//alert(element);
if (val == 'male' ) {
document.getElementById('gb').style.display = 'block';
} else {
document.getElementById('gb').style.display = 'none';
}
}
</script>
After isValid = true; wrap the rest of the code just before return isValid; in an if loop if(document.getElementById('gb').style.display == "block") { /*[ your validation]*/
}
And your HTML code is incorrect. You cannot directly have a td inside another td. Its good practice if you put span or div or p or anyother element instead of the td's inside <td id="gb" style="display:none;">.
call validateStep() function only when the two fields are visible.
if($('#msg_name').is(":visible")){
validateStep ();
})

Javascript onload event function is working only on server restart

I have written a function in Javascript which will be fired on page load.
The function works fine for the first time. But if I come back to index page after visiting other pages, it does not work properly.
It does work correctly upto a certain point but skips code after that.
following is my function
<script>function populate() {
//alert("The Flag is "+$('#flag').val());
val =document.getElementById('flag').value;
xml =document.getElementById('xml').value;
alert(xml);
if (val === "M") {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(xml);
alert("ActiveX");
} else {
var parser = new DOMParser();
doc = parser.parseFromString(xml, 'text/xml');
// alert("DOMparser");
}
alert("Value true");
/* upto here function works correctly each time
* I have also seen the values of both val and xml are coming correctly
*/
passportNo = doc
.getElementsByTagName('PASSPORT_NO')[0].childNodes[0].nodeValue;
//alert('passportNo ' + passportNo);
document.getElementById('passportNo').value = passportNo;
pass_type = doc.getElementsByTagName('PASS_TYPE')[0].childNodes[0].nodeValue;
// alert("Pass_type = " + pass_type);
if (pass_type === "I") {
document.getElementById('in').checked = true;
} else if (pass_type === "O") {
document.getElementById('out').checked = true;
}
jobNo = doc.getElementsByTagName('JOB_NO')[0].childNodes[0].nodeValue;
//alert("jobNo = "+jobNo);
document.getElementById('job_no').value = jobNo;
jobDt = doc.getElementsByTagName('JOB_DT')[0].childNodes[0].nodeValue;
//alert("jobDT "+jobDt);
document.getElementById('DT').value = jobDt;
//Clear xml
nationality =doc.getElementsByTagName('NATIONALITY')[0].childNodes[0].nodeValue;
document.getElementById('nationality2').value = nationality;
element = document.getElementById('nationality');
element.value = nationality;
}
} </script> `
and this is how I am calling it
<body onload="populate()">
<table width="1270" align="center">
<tr>
<td width="1010" height="46" colspan="3" align="center"><h1>Currency
Declaration Form</h1></td>
</tr>
</table>
<input type="hidden" id="flag" value="<%=code%>" />
<input type="hidden" id="xml" value="<%=xml%>" />
<form name="myForm" action="Entry.do" method="post"
onsubmit="return validateAll()" class = "autocompleteOff">
<table width="1042">
<tr class="heading">
</tr>
<tr>
<td width="256" align="left"><input type="radio" name="inout"
id="in" value="I" /> <label>INCOMING </label> <input type="radio"
name="inout" id="out" value="O" /> <label>OUTGOING </label></td>
<td width="774" align="right"><label>JobNo/DT</label> <input
type="text" name="job_no" id="job_no" readonly="readonly"
tabindex="-1" /> <input type="text" name="DT" id="DT"
readonly="readonly" tabindex="-1" value="<%=Convert.getSysDate()%>" /></td>
</tr>
</table>`
I can't see neither passportNo id neither PASSPORT_NO tag (getElementsByTagName) in your HTML code. Same problem with pass_type, nationality and many other elements. Do you miss some code? Or, maybe, this is dynamic output from PHP (for example) and after first run it returns different HTML?

iterating through imput elements to assign values to an array

The code below fetches a list of files that have been selected for upload.
It basically appends input elements inside a div above a form element:
<div id = "files_list"> </div>
How do I store all the attributes names in an array - fileNamesArray - on clicking the submit button.?
My attempt I'm yet to check if this works:
// beginning of attempt
// my approach:
// alert the user if no file is selected for upload and submit is clicked else
// I'd have to iterate through the input elements and contained in the div id="files_list", fetch all the file names and push all the values into an array $filesArray.
//rough attempt
$("Submit").click(function () {
$filesArray
$(div#files_list).getElementById('input').each(function($filesArray) {
filesArray.push($this.attr("value"))
});
while( $filesArray.size != 0) {
document.writeln("<p>" + $filesArray.pop() + "</p>");
}
}
//end of attempt: I print out the names just to verify
Code Below:
$(document).ready(function(){
var fileMax = 6;
$('#asdf').after('<div id="files_list" style="border:1px solid #666;padding:5px;background:#fff;" class="normal-gray">Files (maximum '+fileMax+'):</div>');
$("input.upload").change(function(){
doIt(this, fileMax);
});
});
function doIt(obj, fm) {
if($('input.upload').size() > fm) {alert('Max files is '+fm); obj.value='';return true;}
$(obj).hide();
$(obj).parent().prepend('<input type="file" class="upload" name="fileX[]" />').find("input").change(function() {doIt(this, fm)});
var v = obj.value;
if(v != '') {
$("div#files_list").append('<div>'+v+'<input type="button" class="remove" value="Delete" style="margin:5px;" class="text-field"/></div>')
.find("input").click(function(){
$(this).parent().remove();
$(obj).remove();
return true;
});
}
};
Code for the HTML form:
<td><form action="test.php" method="post" enctype="multipart/form-data" name="asdf" id="asdf">
<div id="mUpload">
<table border="0" cellspacing="0" cellpadding="8">
<tr>
<td><input type="file" id="element_input" class="upload" name="fileX[]" /></td>
</tr>
<tr>
<td><label>
<textarea name="textarea" cols="65" rows="4" class="text-field" id="textarea">Add a description</textarea>
</label></td>
</tr>
<tr>
<td><input name="Submit" type="button" class="text-field" id="send" value="Submit" /></td>
</tr>
</table><br />
</div>
</form>
<p class="normal"></td>
var my_array = new Array();
$('#asdf').bind('submit', function() {
$.each(this.elements, function() {
if ( this.type == 'file' ) {
$('#file_list').append($(this).clone());
my_array.push(this.value);
}
});
for ( var i=0; i < my_array.length; i++ )
alert(my_array[i]);
});
Here you go!
EDIT Updated due to OP's comment.

Categories