Javascript function stops working when adding int - javascript

I'm making system where questions can be answered trough a select box system. It works so far
function changedValue(vraagId) {
currentId = document.getElementById(vraagId+1).value;
valueId = document.getElementById(vraagId).value;
if (currentId == "") {
document.getElementById(valueId+1).disabled = true;
document.getElementById(valueId+2).disabled = true;
document.getElementById(valueId+3).disabled = true;
document.getElementById(valueId+4).disabled = true;
document.getElementById(vraagId+1).value = valueId;
}
else {
document.getElementById(valueId+1).disabled = true;
document.getElementById(valueId+2).disabled = true;
document.getElementById(valueId+3).disabled = true;
document.getElementById(valueId+4).disabled = true;
document.getElementById(currentId+1).disabled = false;
document.getElementById(currentId+2).disabled = false;
document.getElementById(currentId+3).disabled = false;
document.getElementById(currentId+4).disabled = false;
document.getElementById(vraagId+1).value = valueId;
}
}
function removeValue(vraagId) {
currentId = document.getElementById(vraagId+1).value;
document.getElementById(currentId+1).disabled = false;
document.getElementById(currentId+2).disabled = false;
document.getElementById(currentId+3).disabled = false;
document.getElementById(currentId+4).disabled = false;
document.getElementById(vraagId+1).value = "";
if (vraagId == 'vraag1') {
document.getElementById('antwoord01').selected = true;
}
if (vraagId == 'vraag2') {
document.getElementById('antwoord02').selected = true;
}
if (vraagId == 'vraag3') {
document.getElementById('antwoord03').selected = true;
}
if (vraagId == 'vraag4') {
document.getElementById('antwoord04').selected = true;
}
}
But now I want to add a system that enables a button when all questions are answered. I've come up with a system that uses an int. As soon as a question is answered, it adds 1. As soon as a question is unanswered, it removes 1. However, when I add int beantwoord = 0; to my script it gives me the error
Uncaught ReferenceError: changedValue is not defined
How can I fix this?

JavaScript is dynamically-typed (variable can hold different types of data), so the following statement will throw an error:
int someVar = 1;
Instead, declare your variable using var, e.g.
var someVar = 1;

Related

Why does this form keep on submitting even if it fails the validation?

I am new to javascript. I would like someone to explain to me why this form keeps getting submitted even if it fails the validation? I am not allowed to use any validation plugins hence I wrote several functions for validation.
/* EMAIL VALIDATION */
let validateEmailInput = (anEmail) => {
let emailRegex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (anEmail.value.search(emailRegex) !== -1 || anEmail.value.match(emailRegex)) {
document.getElementById("errorOutput1").innerText = "";
return true;
} else {
document.getElementById("errorOutput1").innerText = "Invalid email!";
anEmail.focus();
return false;
}
}
/* RADIO VALIDATION */
let validateRadioInput = (name) => {
let radios = document.getElementsByName("part1_radio");
let isCheckedRadio = false;
let numRadioChecked = 0;
let radioChosen;
for (let i = 0; i < radios.length && !isCheckedRadio; i++) {
if (radios[i].checked) {
numRadioChecked++;
document.getElementById("errorOutput2").innerText = "";
radioChosen = radios.item(i).id;
isCheckedRadio = true;
}
} //end for
if (numRadioChecked === 0) {
document.getElementById("errorOutput2").innerText = "Please select one season!";
isCheckedRadio = false;
}
return isCheckedRadio;
}
/* CHECKBOX VALIDATION */
let validateCheckboxInput = (name) => {
let checkboxGroup = document.getElementsByName("part1_checkbox");
let isCheckedCheckbox = false;
let numCheckboxChecked = 0;
let checkboxChosen;
for (let i = 0; i < checkboxGroup.length && !isCheckedCheckbox; i++) {
if (checkboxGroup[i].checked) {
numCheckboxChecked++;
document.getElementById("errorOutput3").innerText = "";
checkboxChosen = checkboxGroup[i];
isCheckedCheckbox = true;
} else {
// if (numCheckboxChecked === 0) {
document.getElementById("errorOutput3").innerText = "Please check at least one country!";
isCheckedCheckbox = false;
}
} // end for
return isCheckedCheckbox;
}
/* SELECT/OPTIONS VALIDATION */
let validateSelectInput = (aSelection) => {
let selectGroup = document.getElementsByName("part1_select");
let isCheckedSelect = false;
let numCheckedSelect = 0;
let selectedVar;
if (!selectGroup.value) {
document.getElementById("errorOutput4").innerText = "Please choose one!";
isCheckedSelect = false;
} else {
isCheckedSelect = true;
selectedVar = selectGroup.value;
}
return isCheckedSelect;
}
This function is called inline like this:
<form id="myForm_part1" name="myForm_part1"action="someemailhere" method="post" onsubmit="validateForm(this.form);" novalidate>
I need help understanding why this happens.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function() {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
return false;
}
});
}
There is an issue with the onsubmit handler. Try changing
onsubmit="validateForm(this.form);"
to
onsubmit = "return validateForm(this.form);"
Without the return statement the submit handler, which is a function compiled from the attribute value, returns undefined because it doesn't have a return statement.
Use preventDefault() to stop submission if validation fails.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function(event) {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
event.preventDefault();
}
});
}

value is not added to multidimensional array

The first time the function fires I get this result:
output1:test
The output2 2 alert is not firing. I know something is probably undefined in alert Does anyone know why the value won't be added in the multidimensional array?
I expect this to display after the false1:
output2:test2
Also if you want to fiddle with the code here it is:
https://jsfiddle.net/ndf0sjgf/1/
var carSelectedArray = [
[null]
];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
} else {
arrayempty = false;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}
Your loop works well, however your didn't define your array well.
there is only 1 dimension here :
var carSelectedArray = [[null]];
So replace with this :
var carSelectedArray = [[],[]];
PS : null is not required
and at the beginning in your function, you define arrayempty to false, so you can remove this :
else {
arrayempty = false;
}
Solution here : https://plnkr.co/edit/Qikalr0jc54R3MRSea4G?p=preview
var carSelectedArray = [[],[]];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}

Form validation JavaScript not working

My form validation function is not working properly. The error msg displayed in the innerHTML element goes away as soon as it appears, like the page is being refreshed.I am new in javascript. I don't know whet seems to be the problem.
<script type="text/javascript">
function validate(form) {
var user = form.txtUsername;
var institute = form.txtinstitute;
var email = form.txtemail;
var pass1 = form.pwdpassword1;
var pass2 = form.pwdpassword2;
var check = "";
check = validateFilled(pass2);
check = validateFilled(pass1);
check = validateFilled(email);
if (check == true) {
check = validateEmail(email);
}
check = validateFilled(institute);
check = validateFilled(user);
if (checked == false) {
return false;
}
//return true;
}
function validateFilled(control) {
if (control.value.length == 0) {
document.getElementById(control.id).nextSibling.innerHTML = "* required";
document.getElementById(control.id).focus();
return false;
}
return true;
}
function validateEmail(control) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!(re.test(email.value))) {
document.getElementById(email.id).nextSibling.innerHTML = " *invalid email";
document.getElementById(email.id).focus();
return false;
}
return true;
}
</script>
check = validateFilled(pass2);
check = validateFilled(pass1); //overrides check above
check = validateFilled(email); //overrides check above
if (check == true) {
check = validateEmail(email);//overrides check above
}
if (check == true) {
check = validateEmail(email);//overrides check above
}
check = validateFilled(institute);//overrides check above
check = validateFilled(user);//overrides check above
So if any of those are false, the other checks under it will make it true. Bad design....
You need to only set check to false if the validation fails....

Javascript 'console' infinite loop

I'm experimenting with javascript programs and I hit a snag. The program suddenly lags my browser (infinite loop maybe), dunno why.
function fullscreen() {
if (document.body.requestFullScreen) {document.body.requestFullScreen();}
else if (document.body.webkitRequestFullScreen) {document.body.webkitRequestFullScreen();}
else if (document.body.mozRequestFullScreen) {document.body.mozRequestFullScreen();}
}
var bash = document.createElement('span');
bash.setAttribute('id', 'bash');
document.body.appendChild(bash);
var cursor = document.createElement('span');
cursor.setAttribute('id', 'bashCursor');
cursor.textContent = '_';
cursor.style.display = 'none';
cursor.style.fontWeight = 'bold';
document.body.appendChild(cursor);
window.Bash = {};
window.Bash.printing = false;
window.Bash.queue = Array();
window.Bash.span = bash;
window.Bash.span.cursor = cursor;
delete bash; delete bash;
function bashPrint() {
window.Bash.writing = true;
var bash = window.Bash.span
var i;
while (window.Bash.queue.length) {
if (window.Bash.queue[0] == undefined) {
i = 0;
while (i < window.Bash.queue.length) {
window.Bash.queue[i] = window.Bash.queue[i+1];
console.log('l:'+window.Bash.queue.length);
console.log(window.Bash.queue);
delete window.Bash.queue[i+1];
window.Bash.queue.splice(i,1);
i++;
}
} else if (window.Bash.queue[0]['type'] == 'instant') {
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
} else if (window.Bash.queue[0]['type'] == 'wait') {
setTimeout(bashPrintWaiting, window.Bash.queue[0]['wait']);
break;
} else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
} else {
window.Bash.span.cursor.style.display = 'none';
}
}
}
window.Bash.writing = false;
}
function bashPrintWaiting() {
window.Bash.writing = true;
var bash = window.Bash.span;
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
window.Bash.writing = false;
setTimeout(bashPrint, 0);
}
function bashWrite(string) {
var array = Array();
array['type'] = 'instant';
array['value'] = string;
window.Bash.queue[window.Bash.queue.length] = array
}
function bashPause(times, string) {
if (!string) {string='';}
while (times > 0) {
var array = Array();
array['type'] = 'wait';
array['value'] = string;
array['wait'] = 50 + Math.floor(Math.random()*450);
window.Bash.queue[window.Bash.queue.length] = array;
times--;
}
}
function bashCursor(enabled) {
var array = Array();
array['type'] = 'cursor';
array['value'] = enabled;
window.Bash.queue[window.Bash.queue.length] = array;
}
bashWrite('Uncompressing');
bashPause(12, '.');
bashWrite('OK\n');
bashPause(3);
bashWrite('Build v. 0.1.01-release (x86_64-pc)\n');
bashPause(2);
bashWrite('Connecting');
bashPause(35, '.');
bashWrite('Error, unknown user. See connect.log for futher information.\n');
bashPause(2);
bashWrite('none#m ~ $ >>');
bashCursor(true);
bashPrint();
I uploaded it on jsFiddle - http://jsfiddle.net/uQcCP/
Program freezes between:
bashWrite('Error, unknown user. See connect.log for futher information.\n');
and
bashPause(2);
Please, can you help me? Thanks a lot.
The infinite loop starts on line 51: while (window.Bash.queue.length) {
It then ends up in the if statement on line 74, and within this the queue is never shortened:
else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
If you find yourself having infinite loop problems in Chrome, open up your development tools and go to the script tab before you open up the page. After you open up the page and it starts looping, you can click the pause button to throw a breakpoint wherever the code is currently executing. From there it's a lot easier to divine where you're getting your error.

javascript - Failed to load source for: http://localhost/js/m.js

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.

Categories

Resources