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?
Related
Ok so I have this email sign up form that I use on my website. I got the script directly from the email management system as they are the ones that process the form.
I'm using it on my website and it works perfectly but when I try and run the same script in a Facebook App it fails to submit. Actually that's not strictly true as it does pop up with the 'You need to agree to the terms...' if left unchecked but it doesn't get any further than that.
I've tested it in a browser and it works so I know there's nothing wrong with the code, I'm just baffled as to why it won't function in Facebook.
Here is the script exactly how it appears on the page.
<form action="http://www.elabs12.com/functions/mailing_list.html" method="post" name="UPTml807" onSubmit="return (!(UPTvalidateform(document.UPTml807)));">
<input type="hidden" name="submitaction" value="3">
<input type="hidden" name="mlid" value="807">
<input type="hidden" name="siteid" value="2012000210">
<input type="hidden" name="tagtype" value="q2">
<input type="hidden" name="demographics" value="1,2,-1,40836,37592">
<input type="hidden" name="redirection" value="http://www.MYWEBISTE.com/WebContent/Promotions/PromotionsNewEmailThanks.htm">
<input type="hidden" name="uredirection" value="http://">
<input type="hidden" name="welcome" value="">
<input type="hidden" name="double_optin" value="">
<input type="hidden" name="append" value="on">
<input type="hidden" name="update" value="on">
<input type="hidden" name="activity" value="submit">
<div class="textfield">
<table border="0" cellspacing="0" cellpadding="5" width="100%">
<tr>
<td><span class="formText">Your First Name*</span><br/><input type="text" name="val_1" class="firstName" size="10" value="" /></td>
<td><span class="formText">Your Last Name*</span><br/><input type="text" name="val_2" class="lastName" size="10" value="" /></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Email*</span><br/><input type='text' name='email' class="email" value='' style='display:block'/></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Mobile Number</span><br/>
<input type='text' name='val_3' class="mobile" value='' style='display:block'/></td>
</tr>
<tr>
<td><div style="text-align:left; margin:0 0 20px 0px"><input type="checkbox" id="val_37592" name="val_37592" style="width:20px; height:10px;">
<span class="formText">I accept your Privacy Policy (below)*</span><br/><br/><span style="font-size:12px !important;" class="formText">*Required field</span></div></td>
<td align="right"><input type="submit" name="submit" value="Submit" class="submitBTN" /></td>
</tr>
</table>
</div>
<script language="Javascript">
function emailCheck (emailStr) {
var emailPat=/^(.+)#(.+)$/;
var specialChars="\\(\\)<>#,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert("Email address seems incorrect (check # and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.");
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
var domainArray=domain.match(domainPat);
if (domainArray==null) {
alert("The domain name doesn't seem to be valid.");
return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1] != "info") &&
(domArr[domArr.length-1] != "name") &&
(domArr[domArr.length-1] != "arpa") &&
(domArr[domArr.length-1] != "coop") &&
(domArr[domArr.length-1] != "aero")) {
if (domArr[domArr.length-1].length<2 ||
domArr[domArr.length-1].length>3) {
alert("The address must end in a three-letter domain, or two letter country.");
return false;
}
}
if (len<2) {
var errStr="This address is missing a hostname!";
alert(errStr);
return false;
}
return true;
}
function UPTvalidateform(thisform)
{
if (document.getElementById("val_37592").checked==false){alert("Please let us know you have read and agree to the Terms and Conditions of this email alert sign up"); return(true);}
if (thisform.val_1.value==""){
alert("Please enter a value for First Name");
return(true);}if (thisform.val_2.value==""){
alert("Please enter a value for Last Name");
return(true);}
if (emailCheck(thisform.email.value))
{
if ((document.getElementById('unsubscribe')
&& document.getElementById('unsubscribe').checked) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")) {
alert('Thank you, now you are unsubscribed!');
}
else if(( (document.getElementById('unsubscribe')
&& !document.getElementById('unsubscribe').checked) || (!document.getElementById('unsubscribe')) ) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")){
alert('Thank you for signing up!');
}
return false;
}
else
{
return true;
}
}
</script>
</form>
I've tried removing the JS to see if Facebook was blocking it and I just get the same result. I've even tried submitting to a different URL but no luck.
Is there something I've missed/am I being blind? Or maybe it's a deeper issue...
Any help is much appreciated.
Thank you.
The url you submit to must be registred in the app details. Try changing the app domains in facebook developers.
Further more if you're browsing facebook in secure mode (default setting) it will block all content from non-ssl urls. so http://www.elabs12.com/functions/mailing_list.html would have to be https://www.elabs12.com/functions/mailing_list.html
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>
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">  <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" >  <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" >  <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.
I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.
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.