Javascript if statement using method from an external file - javascript

I have multiple pages with identical form validation, so I have moved it to an external js file. My call to the method (validateFormFill() is in file GARIValidateFormFill.js) within the external file is
$("#submitForm").click(function(){
if (validateFormFill()) {
//code
}
});
When I now call validateFormFill, nothing happens. I do have my js file properly linked within my jsp.
What do I need to do to read the external file in my if statement?
Edit
Here is more per request.
My file is linked properly: <script src="${pageContext.request.contextPath}/javascript/GARIValidateFormFill.js"></script>
Within my external file I have:
function validateFormFill() {
// Make sure at least one file is entered
var blnAtLeastOneFileSelected = false;
for (var i=0; i < $('#numOfFiles').val(); i++) {
var index = i+1;
// Reset the amount to contain no commas prior to submitting the form.
if ($('#txtFile' + index).is(':checked')) {
blnAtLeastOneFileSelected = true;
break;
}
}
if ( ! blnAtLeastOneFileSelected ) {
alert("ERROR! Please select at least one file before submitting the form!");
return false;
}
var ckdt = checkDate($('#txtReportDate').val())
if ( ckdt == false ) {
return false;
}
if($('#txtVersionNum').val() == "00.00" || $('#txtVersionNum').val().length == 0) {
alert("ERROR! Version No. must be entered before submitting form!");
$('#txtVersionNum').focus();
return false;
}

You need to add the reference in a <script> tag before the validateFormFill() is executed.
Without much knowledge of validateFormFill, I am assuming you're looking for something more like...
<script src="path/to/GARIValidateFormFill.js"></script>
<script>
$("#submitForm").click(function(){
if (validateFormFill()) {
//code
}
});
</script>
Script Tag

I found the problem. I was missing a closing } in my external file

Related

Is that possible to put Template7 code in a separate file rather than in html

I am using a framework called Framework7.
In my index.html, I have some Template7 code, like this format
<script type="text/template7" id="commentsTemplate">
{{#each this}}
<div> test this template 7 code </div>
</script>
However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).
I have tried to use a typical way to import js
<script type="text/template7" id="storiesTemplate" src="js/template.js"></script>
But it doesn't work, there is also no demo/sample code in the documentation.
Any help is appreciated!
You can do it. The idea behind is to include a HTML file in a HTML file. I can tell at least 3 ways that this can happen, but personally I fully validated only the third.
First there is a jQuery next sample is taken from this thread
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
Another solution, I found here and doesn't require jQuery but still it's not tested: there is a small function
My solution is a pure HTML5 and is probably not supported in the old browsers, but I don't care for them.
Add in the head of your html, link to your html with template
<link rel="import" href="html/templates/Hello.html">
Add your template code in Hello.html. Than use this utility function:
loadTemplate: function(templateName)
{
var link = document.querySelector('link[rel="import"][href="html/templates/' + templateName + '.html"]');
var content = link.import;
var script = content.querySelector('script').innerHTML || content.querySelector('script').innerText;
return script;
}
Finally, call the function where you need it:
var tpl = mobileUtils.loadTemplate('hello');
this.templates.compiledTpl = Template7.compile(tpl);
Now you have compiled template ready to be used.
=======UPDATE
After building my project for ios I found out that link import is not supported from all browsers yet and I failed to make it work on iphone. So I tried method number 2. It works but as you might see it makes get requests, which I didn't like. jquery load seems to have the same deficiency.
So I came out with method number 4.
<iframe id="iFrameId" src="html/templates/template1.html" style="display:none"></iframe>
and now my loadTemplate function is
loadTemplate: function(iframeId, id)
{
var iFrame = document.getElementById(iframeId);
if ( !iFrame || !iFrame.contentDocument ) {
console.log('missing iframe or iframe can not be retrieved ' + iframeId);
return "";
}
var el = iFrame.contentDocument.getElementById(id);
if ( !el ) {
console.log('iframe element can not be located ' + id );
return "";
}
return el.innerText || el.innerHTML;
}
How about lazy loading and inserting through the prescriptions?
(function (Template7) {
"use strict";
window.templater = new function(){
var cache = {};
var self = this;
this.load = function(url)
{
return new Promise(function(resolve,reject)
{
if(cache[url]){
resolve(cache[url]);
return true;
}
if(url in Template7.templates){
resolve(Template7.templates[url]);
return true;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
cache[url] = Template7.compile(this.response);
resolve(cache[url]);
}else{
reject(`Template ${url} not found`);
}
};
xhr.send();
})
}
this.render = function(url, data)
{
return self.load(url)
.then(function(tpl){
return tpl(data) ;
});
}
this.getCache = function()
{
return cache;
}
}
})(Template7);
Using :
templater.render('tpl.html').then((res)=>{ //res string })
Or :
templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )
It is possible to define your templates in .js-files. The template just needs to be a string.
Refer to this [JSFiddle] (https://jsfiddle.net/timverwaal/hxetm9rc/) and note the difference between 'template1' and 'template2'
var template1 = $$('#template').html();
var template2 = '<p>Hello, my name is still {{firstName}} {{lastName}}</p>'
template1 just extracts the content of the <script> and puts it in a string.
template2 directly defines the string

Javascript file will not load

I have a simple script that works when included in the html body. However, when running this from a relative path, and including the
<script type="text/javascript" src="simple.js"></script>
in either the header or bottom of the html file, the script will no longer run.
Can anyone point as to what I am missing ?
Thank you.
Script simple.js:
<script>
function firstFunction(){
var a = document.getElementById("firstInput").value;
if(! a){
alert("minimum input of 1 char required");
}else{
document.getElementById("firstOutput").innerHTML=a;
}
}
function secondFunction(){
var b = document.getElementById("secondInput").value;
if(!b){
alert("minimum input of 1 char required");
}
document.getElementById("secondOutput").innerHTML=b;
//document.getElementById("secondOutput").innerHTML = "updated!";
}
You only need the <script> tag if you include the javascript into your html file.
In a .js file, it's a syntax error. Just write your javascript code without the tag!
File simple.js:
function firstFunction(){
var a = document.getElementById("firstInput").value;
if(!a){
alert("minimum input of 1 char required");
}else{
document.getElementById("firstOutput").innerHTML=a;
}
}
function secondFunction(){
var b = document.getElementById("secondInput").value;
if(!b){
alert("minimum input of 1 char required");
}
document.getElementById("secondOutput").innerHTML=b;
//document.getElementById("secondOutput").innerHTML = "updated!";
}
As your file is right now, make sure to place the script right before the closing body tag
<script type="text/javascript" src="simple.js"></script>
</body>
so that the elements can be found when the script is running.

Validate that a xml file is a file with javascript before submitting

Let's say I have an xml file I want to upload through a html form using php but I want to verify first that the xml file is an actual file using javascript. I have a form with only one input and this piece of javascript code:
function Validate(form) {
var _validFileExtensions = [".xml"];
var arrInputs = form.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert(oInput.type);
//alert("Lo siento, " + sFileName + " es invalido, la única extensión permitida es: " + _validFileExtensions.join(", "));
return false;
}
}
}else{
alert(oInput.type);
//alert("Tienes que seleccionar un archivo");
return false;
}
}
return false;
}
I'm just putting this piece to describe the problem, which is that file.xml isn't a file, is empty, if I try to submit any type of file that I can find on my computer, like "javascript.js", "newdocument.txt" or any kind of file, javascript "file.type" does match "file", but if I submit a "file.xml" it alerts "submit", same thing if I click submit without selecting any file. Which leads me to believe that .xml files are treated as some kind of instruction or something.
I know I also have to validate server side and stuff, but for now I want to validate client side using javascript, so, is there a way to validate that "file.xml" is a file?
EDIT: (Added full code and fiddle>
HTML:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<title>XML a PDF</title>
<script type="text/JavaScript" src="javita.js"></script>
</head>
<body>
<form action="transforma.php" method="post" mimetype="text/xml" enctype="text/xml" onsubmit="return Validate(this);" name="transforma">
<label for="file">Filename: </label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Also tried with:
<form action="transforma.php" method="post" enctype="multipart/form-data" onsubmit="return Validate(this);" name="transforma">
Same result
Fiddle
If you have not realized it yet, you're just totally looking in the wrong direction with the assumptions you do.
First of all, javascript does not differ on the contents of a string here. It just operates on a string. Whether that string contains "I hate you javascript, go home" or "this-file-extension-is-better-than-others.txt" or your so missing "file.xml" - it will always work the same here.
See this comment of yours two days ago:
I'm more interested on knowing is why a xml file isn't recognized as a file by javascript, or how can I accomplish javascript to acknowledge a xml file as a file.
So I let you know: The XML file is recognized as a file by javascript.
After I have introduced that knowledge to you (and I hope you're openhearted accepting this to know, too, as it solves the largest part of your problem), then let's see what's going on here.
First of all you're doing too many things at once. For example, you'd like to get the file input element. As it doesn't have an ID you iterate through all inputs. That's just not necessary. If the problem is that the element can't well be identified, give the form an ID so that you can:
form.id || (form.id = "id".concat(+new Date, parseInt(Math.random() * Math.pow(10, 16))));
var fileName = document.querySelector("#".concat(form.id, " input[type=file]")).value;
Done. There is the string of the fileName. If you then verify this, you can easily see that it always contains the filename. If not yet choosen, it's an empty string, if choosen, it's the "fakepath" string of the filename. At least at this point you have to realize that it always will be a string, regardless of which file you've been chosen.
Next thing is that you should create a function that validates a filename's extension against your whitelist. This has the benefit, that you can just use it on any string no matter where you got it from:
var fileExtension = function (file) {
var extensions = [".xml"];
var match;
extensions.every(function (extension) {
var e = /([.*+?^=!:${}()|\[\]\/\\])/g;
if (new RegExp(extension.replace(e, "\\$1") + '$', 'i').test(file)) {
match = extension;
return false;
}
return true;
});
return match;
}
When done this, you can easily validate the form, see this working fiddle: http://jsfiddle.net/JZj85/
It's not entirely foolproof but you could try this:
function validate(form) {
var file = form.getElementsByTagName("input")[0];
var ext = file.value.substring(file.value.lastIndexOf('.'));
if (ext == "xml") {
// Do something when it is an xml file
} else {
// Do something else when it is not
}
return false
}
.getElementsByTagName returns an array of elements. You want the first one since that is your file input.
var ext = ... gets the extension, or at least what is behind the last . (including). But a user can still upload another filetype but just change the extension, so you need some serverside validation as well.
See Fiddle

HTML with XML using jQuery

i have xml file which contains lots of data. now i want to pick a price with some condition. i set a parameteres in javascript function but it is not giving desire result. i think it can be done through childnode but i didnot aware about that
XML file
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="PER" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="SYD" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
HTML page
<head>
<script type="text/javascript">
function myXml(origin, destination ) {
var x = xmlDoc.getElementsByTagName("flights");
for(i=0; i<x.length; i++) {
if (x[i].getAttribute('FrTLAs') == origin
&& x[i].getAttribute('destination') == destination) {
alert(x[i].getAttribute('price'))
}
}
}
</script>
</head>
<body>
click me
</body>
did u miss this??
xmlDoc=loadXMLDoc("flights.xml");
chk this page
http://www.w3schools.com/dom/prop_element_attributes.asp
the example2 is very clear how to use this
x=xmlDoc.getElementsByTagName("book")[0].attributes;
//here its would be getElementsByTagName("flights") in the loop
//then .attributes on it
// and then this
frtlas=x.getNamedItem("FrTLAs");
desti=x.getNamedItem("destination");
//and your code here
hope this helps

why does this regex work outside of a javascript function but not inside of it?

Okay so I'm kind of new to regexps in general, let alone in Javascript.
I am trying to work on a form validation project and I found a site where they have a list of useful sample regexps for various things here which has a few for email validation, which is what I'm attempting at the moment.
Anyway, following this example for form validation on w3schools I was able to get it working properly using their example and the regexp works outside of the javascript function, but for some reason when I call it inside the function it returns a value of undefined.
Here's my code:
<html>
<head>
<title>formzz validate-jons</title>
<script type="text/javascript">
pattern = new RegExp("^[0-9a-zA-Z]+#[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
function valid8email(field, txt)
{
with(field)
{
//at_pos = value.indexOf('#');
//dot_pos = value.lastIndexOf('.');
if(!pattern.test(value)) //at_pos < 1 || (dot_pos - at_pos) < 2)
{
alert(txt);
return false;
}
else
{
return true;
}
}
}
function valid8(form)
{
with(form)
{
if(valid8email(email, "you must enter an email address") == false)
{
email.focus();
return false;
}
}
}
</script>
</head>
<body>
<form action="#" method="POST" onsubmit="return valid8(this)">
Email: <input type="text" name="email" size="30" />
<input type="submit" value="clicky-click" />
</form>
<script type="text/javascript">
alert(pattern.test(""));
</script>
</body>
</html>
Okay... so the alert in the script tags inside the body works just fine.
I've done numerous tests inside the javascript function itself and checked various things:
the type of 'value' is String
the function returns 'undefined' when called inside the javascript
the regex itself works fine as it will return true when the proper formatting is entered in the script tags below
So what could the issue be? I am confused.
The problem is that pattern refers to field.pattern (an HTML5 attribute) because you're using it inside the with(), and that's a string, not your regex. If you called it something else like pattern1, it would work fine.
That being said, don't use with in the first place, and you won't have these issues :)
The non-with version looks like this:
var pattern = new RegExp("^[0-9a-zA-Z]+#[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
function valid8email(field, txt) {
if (!pattern.test(field.value))
{
alert(txt);
return false;
}
else {
return true;
}
}
function valid8(form) {
if (valid8email(form.email, "you must enter an email address") == false) {
form.email.focus();
return false;
}
}
You can test it out here.

Categories

Resources