I don't know why there is a warning of "Move variable declaration to top of function or script."
Although I move the variable "myName" to other places, the variable below will be the new one having the same warning. I have input "window, document" in the "Options" section in JSlint.
window.onload = function() {
"use strict";
var myLogin = document.forms.submitForm;
myLogin.onsubmit = processForm;
var myName = document.getElementById("result__username");
var myPassword = document.getElementById("result__password");
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
function processForm() {
var in_username = myLogin.username;
var in_password = myLogin.password;
if (in_username.value === "") {
in_username.classList.add("changered");
in_username.focus();
return false;
}
in_username.classList.add("changewhite");
if (in_password.value === "") {
in_password.classList.add("changered");
in_password.focus();
return false;
}
in_password.classList.add("changewhite");
myName.innerHTML = in_username.value;
myPassword.innerHTML = in_password.value;
myMessage.classList.add("displayblock");
return false;
}
};
If you are going to use a linter, you need to follow what ever rules you have applied. You need to move the vars before you touch the variables. You need to indent right. Set up your IDE with plug ins that will format your code for you.
window.onload = function () {
"use strict";
var myLogin = document.forms.submitForm;
var myName = document.getElementById("result__username");
var myPassword = document.getElementById("result__password");
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
myLogin.onsubmit = processForm;
function processForm() {
var in_username = myLogin.username;
var in_password = myLogin.password;
if (in_username.value === "") {
in_username.classList.add("changered");
in_username.focus();
return false;
}
in_username.classList.add("changewhite");
if (in_password.value === "") {
in_password.classList.add("changered");
in_password.focus();
return false;
}
in_password.classList.add("changewhite");
myName.innerHTML = in_username.value;
myPassword.innerHTML = in_password.value;
myMessage.classList.add("displayblock");
return false;
}
};
Related
I get this JSON error that tells me that I have a syntax error an I can't figure out where I made the mistake. I have provided the code in case if helps.
var isNode= typeof module !=="undefined"
var clientData;
var auxClientData;
var aux=[];
var k=0;
if (!isNode)
{
var storedObjects=JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);
var ok=false;
buttonConfirm.addEventListener("click",function(){
for(var i=0;i<inputs.length;i++)
{
var inputShow=inputs[i].value;
if (inputShow!=null && inputShow!="")
{
aux[k++]=inputShow;
}
else
{
alert("ALL THE FIELDS MUST BE COMPLETED! ");
ok=true;
break;
}
}
clientData={fullName:aux[0],emailAddress:aux[1],phoneNumber:aux[2]};
//localStorage.setItem("clientData",JSON.stringify(clientData));
// console.log(clientData);
if (ok==true){
alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
}
console.log(JSON.parse(JSON.stringify(clientData)));
})
}
else
{
var clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
var fs=require("fs");
auxClientData=JSON.stringify(clientData);
fs.writeFile("clients.json",auxClientData,finished)
function finished()
{
console.log("ok");
var ok=fs.readFileSync("clients.json");
var test=JSON.parse(ok);
console.log(test);
}
}
Here is the error:
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
I've just realised what the problem is :
var clientData;
auxClientData=JSON.stringify(clientData);
clientData inside your else statement is never set and it will be undefined. so you will need to redefine it inside the else. aux will need to be available and in scope further up your program for this to work. You can confirm my assumption by manually setting clientData to something else inside the else statement.
else
{
var fs=require("fs");
clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
auxClientData=JSON.stringify(clientData);
fs.writeFile("clients.json",auxClientData,finished)
function finished()
{
console.log("ok");
}
var ok=fs.readFileSync("clients.json");
var test=JSON.parse(ok);
console.log(test);
}
------------------------------YOUR CODE.
var isNode = typeof module !== "undefined"
var clientData;
var auxClientData;
var aux = [];
var k = 0;
if (!isNode) {
// INSIDE THE IF
var storedObjects = JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);
var ok = false;
//add a listener inside the if statement for the click.
buttonConfirm.addEventListener("click", function () {
// when it is clicked.
for (var i = 0; i < inputs.length; i++) {
var inputShow = inputs[i].value;
if (inputShow != null && inputShow != "") {
//POPULATE THE AUX ARRAY adding one to k each time?
// seems weird, why is this not aux[i] = inputShow;
aux[k++] = inputShow;
}
else {
alert("ALL THE FIELDS MUST BE COMPLETED! ");
ok = true;
break;
}
}
clientData = { fullName: aux[0], emailAddress: aux[1], phoneNumber: aux[2] };
//localStorage.setItem("clientData",JSON.stringify(clientData));
// console.log(clientData);
if (ok == true) {
alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
}
console.log(JSON.parse(JSON.stringify(clientData)));
})
}
else {
//inside the else.
//aux is an empty array here. so aux[0] = undefined, aux[1] = undefined etc.
//i.e. the button hasn't been pressed to populate it at this point.
var clientData = { "fullName": aux[0], "emailAddress": aux[1], "phoneNumber": aux[2] };
var fs = require("fs");
auxClientData = JSON.stringify(clientData);
fs.writeFile("clients.json", auxClientData, finished)
function finished() {
console.log("ok");
var ok = fs.readFileSync("clients.json");
var test = JSON.parse(ok);
console.log(test);
}
}
I need to evaluate JavaScript expressions, in a browser, Chrome. To make it safe, I use a Blob and a Worker running my evaluator, until it posts back the result of a timeout cancels the wait. This is working fine. I also need to support an environment for my JavaScript. I do this as below:
function evalWorker () {
let postResponse = function(expr, ...) {
let presets = `var EnvObject = {};
EnvObject.platform = "Chrome";
EnvObject.pasteboard = "${clipboard}";
EnvObject.baseDate = new Date();
...
EnvObject._output = "";
EnvObject.appendOutput = (str) => {EnvObject._output += str; };
`
postMessage(eval(presets + expr));
};
onmessage = function(e) {
postResponse(e.data['expression'], e.data['clipboard'], ...);
}
}
My problem is that if _output is not empty, I need to return that - _output instead of the evaluated expression, as in
EnvObject.appendOutput('hello');
var a = 0;
++a;
Should return hello; while without appendOutput, it should return 1.
How would I go about something like this?
#Bergi had the right idea with pushing the scope out. The below works.
function evalWorker () {
let postResponse = function(expr, TextExpander) {
let result = eval(expr);
if (EnvObject._output && EnvObject._output.length) {
postMessage(EnvObject._output);
} else {
postMessage(result);
}
};
onmessage = function(e) {
var EnvObject = {};
EnvObject.platform = "Chrome";
EnvObject.pasteboardText = e.data['clipboard'];
...
EnvObject._output = "";
EnvObject.appendOutput = function(str) {EnvObject._output += str; };
postResponse(e.data['expression'], EnvObject);
}
}
I am a beginner at js and have a project due by the end of day. I have to display an array with temps added and have set up an object to hold this array. My problem is that the message won't display and the for statement doesn't increment. When passed through both the var i and count come back undefined. I know there is a lot missing from this code but at this point I have tried to stream line it so that I can debug this issue. The date I will deal with later.
Here is my code:
var temps = [];
function process() {
'use strict';
var lowTemp = document.getElementById('lowTemp').value;
var highTemp = document.getElementById('highTemp').value;
var output = document.getElementById('output');
var inputDate = (new Date()).getTime();
var temp = {
inputDate : inputDate,
lowTemp : lowTemp,
highTemp : highTemp
};
var message = '';
if (lowTemp == null) {
alert ('Please enter a Low Temperature!');
window.location.href = "temps.html";
} else if (highTemp == null) {
alert ('Please enter a High Temperature!');
window.location.href = "temps.html";
} else {
lowTemp = parseFloat(lowTemp, 10);
highTemp = parseFloat(highTemp, 10);
}
if (temp.value) {
temps.push(temp.inputDate, temp.lowTemp, temp.highTemp)
var message = '<h2>Temperature</h2><ol>';
for (var i = 0, count = temps.length; i < count; i++) {
message += '<li>' + temps[i] + '</li>'
}
message += '</ol>';
output.innnerHTML = message;
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
}
window.onload = init;
Here is my new code:
var temps = [];
function process() {
'use strict';
var lowTemp = document.getElementById('lowTemp').value;
var highTemp = document.getElementById('highTemp').value;
var output = document.getElementById('output');
var inputDate = (new Date()).getTime();
var temp = {
inputDate : inputDate,
lowTemp : lowTemp,
highTemp : highTemp
};
var message = '';
if (lowTemp == null) {
alert ('Please enter a Low Temperature!');
window.location.href = "temps.html";
} else if (highTemp == null) {
alert ('Please enter a High Temperature!');
window.location.href = "temps.html";
} else {
lowTemp = parseFloat(lowTemp, 10);
highTemp = parseFloat(highTemp, 10);
}
if (temp.value) {
temps.push(temp.inputDate, temp.lowTemp, temp.highTemp)
var message = '<h2>Temperature</h2><ol>';
for (var i = 0, count = temps.length; i < count; i++) {
message += '<li>' + temps[i] + '</li>'
}
message += '</ol>';
output.innnerHTML = message;
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
}
window.onload = init;
There are some big issues with your code:
You should never compare anything to NaN directly. The correct comparison should be:
if (isNaN(lowTemp)) {
You're using curly braces when not needed. You should remove both curly braces:
{window.location.href = "temps.html";}
The function parseFloat expects only one parameter: the string to be converted. You're probably confusing it to parseInt which expects both the string and the radix of the conversion.
You're using the temp's property value, but you have never setted it, so, the condition where you check if it exists will always return false, and the push method that you want to debug will never be called, since it's inside that if statement.
Finally, you're closing a li tag at the end, but you have never opened it. You should probably be closing the ol tag you have opened in the begining.
The rest of your code seems pretty OK for me.
Talking about debugging, you should read the Google Chrome's Debugging Javascript Tutorial.
I am learning javascript. When I call pictureArrayAdd method I receive error Picture.pictureArrayAdd is not a function. Why?
window.onload = init;
//window.picture = new Array();
function init() {
var button = document.getElementById("addButton");
button.onclick = addPicture;
}
function Picture() {};
Picture.prototype = {
pictureArray: [],
pictureArrayAdd: function(newImage) {
this.pictureArray.push(newImage);
return this
}
}
var addPicture = function() {
var textInput = document.getElementById ("pictureName");
var newPicture = textInput.value;
Picture.pictureArrayAdd(newPicture);
}
You have to initialize an instace of your object:
var addPicture = function() {
var textInput = document.getElementById ("pictureName");
var newPicture = textInput.value;
var pic = new Picture();
pic.pictureArrayAdd(newPicture);
}
Besides - just a tip -, you can use a optional parameter on your constructor, like this:
function Picture(newImage) {
if (newImage != undefined) {
this.pictureArrayAdd(newImage);
}
};
So you have a shortcut to your pictureArrayAdd function:
var pic = new Picture("picture1.png");
See it working here.
Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.