Just trying to figure out my error of "strange loop". I receive this error in JSLint and the loop just keeps going over and over again whereas it needs to stop.
<script type="text/javascript">
function checkForm(theForm) {
"use strict";
/*global alert*/
var formValid = true,
elementCount = 0;
while (elementCount <= theForm.length) {
if (theForm.elements[elementCount].type === "text") {
if (theForm.elements[elementCount].value() === "") {
alert("Please complete all the form elements");
theForm.elements[elementCount].focus();
formValid = false;
break;
}
}
return formValid;
}
} </script>
Any help or guidance is appreciated, please explain or show me as I am a novice.
As others have said, you need to increment that counter. However it might be clearer with a for loop, which often looks like this:
for (var elementCount = 0; elementCount <= theForm.length; elementCount++) {
// do stuff
}
It's clearer because the incrementing happens right at the top of the for expression.
You're not incrementing elementCount within your loop. Try this:
<script type="text/javascript">
function checkForm(theForm) {
"use strict";
/*global alert*/
var formValid = true,
elementCount = 0;
while (elementCount < theForm.length) {
if (theForm.elements[elementCount].type === "text") {
if (theForm.elements[elementCount].value === "") {
alert("Please complete all the form elements");
theForm.elements[elementCount].focus();
formValid = false;
break;
}
}
elementCount++;
}
return formValid;
}
</script>
Notice that I also moved your return statement outside your loop.
Related
I can't get this working:
var x = 1;
while (x == 1) {
}
function changeX(val) {
if (val == 1) {
x = 1;
} else if (val == 0) {
x = 0;
break;
}
}
and no matter what I do, I can't get this working. What I want to do is: I want the loop to stop working when I choose "0" or type it or anything. I have to use break/continue .
No matter what I do, I get wrong use of break or my browser crashes.
PS. In HTML part I put
<input type="text" value="1" onchange="changeX(this.value)">
Making your code work:
While will block the browsers thread. Therefore, you cannot click.
Do:
var x=false;
function react(){
if(x){return;}
//your code
console.log("sth");//e.g.
setTimeout(react,0);
}
react();
Now you can do your UI stuff
function changeX(val) {
if (val == 0) {
x = true;
}
}
What you really want:
var timer=false;
function input(val){
if(timer){
clearInterval(timer);
timer=false;
}
if(val){
timer=setInterval(function(){
val++;
alert(val);
if(val==10){
clearInterval(timer);
timer=false;
}
}, 1000);
}
<input oninput="input(this.value)">
<h3>Break Statement</h3>
<script>
let num=0;
while(num<5){
num++;
if((num==3)){
break;
}else{
document.write("num is: "+num+"<BR/>")
}
}
document.write("When if condition is true: while Loop Terminated");
</script>
<h3>Continue Statement</h3>
<script>
let val=0;
while(val<5){
val++;
if(val==3){
// skip the current loop iteration and jump to the next iteration
continue;
}
document.write("val = "+val+"<BR/>");
}
</script>
I am trying to create a function that loops infinitely until user inputs that they would like to exit. Every time I open up the webpage in the browser, however, no prompt box appears and the infiniteLoop() function does not execute. Why is the infiniteLoop() function not being called?
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
var tryAgain= prompt("Exit loop?");
if (tryAgain != "Yes") {
infiniteLoop();
}
}
}
You need to call the function in the window onload event.
window.onload = function(){
infiniteLoop();
}
or, if you're using jquery
$(function() {
infiniteLoop();
});
The prompt box doesn't appear because you didn't call the function when your web page loads.
Add infiniteLoop() after you declare your function.
e.g.
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
while (i < 5) {
var tryAgain= prompt("Are you sure?");
if (tryAgain == "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
}
// Initial call
infiniteLoop();
IT WORKS, write 5 times "Yes"(case sensitive) it finishes, otherwise it works infinitely, and do not forget to call infiniteLoop()
Cleaned up and working
(function infiniteLoop() {
var begin = prompt("Shall we begin?");
if (begin === "Yes") {
var i= 0;
while (i < 5) {
var tryAgain = prompt("Are you sure?");
if (tryAgain === "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
})()
The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.
What would I need to add in order for this to validate according to how many checkboxes have been selected? I want the user to select at least two checkboxes before submission of data. Here is my Javascript code:
<script type="text/javascript" language="JavaScript">
function checkCheckBoxes(theForm) {
if (
theForm.Conservatives.checked == false &&
theForm.Labour.checked == false &&
theForm.LiberalDemocrats.checked == false)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
</script>
The current Javascript code only validates if any checkboxes have been selected or not, but I want it to validate for two checkboxes.
Just count how many are checked and see if it's less than 2.
function checkCheckBoxes(theForm) {
var cnt = 0;
if (theForm.Conservatives.checked) ++cnt;
if (theForm.Labour.checked) ++cnt;
if (theForm.LiberalDemocrats.checked) ++cnt;
if (cnt < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
As long as you're only worried about those three checkboxes and you don't want to use a JavaScript library, the easiest thing I can think of would be:
var checkedBoxes = [];
if(theForm.Conservatives.checked)
checkedBoxes.push(theForm.Conservatives);
if(theForm.Labour.checked)
checkedBoxes.push(theForm.Labour);
if(theForm.LiberalDemocrats.checked)
checkedBoxes.push(theForm.LiberalDemocrats;
// two or more boxes are checked
if(checkedBoxes.length < 2){
alert('Choose at least two parties.');
}
else {
// Do stuff with checkedBoxes.
}
This method will not only give you the Count of the number of checked items but will also allow you to access only the checked boxes later in your code if needed.
You can do:
if (theForm.Conservatives.checked +
theForm.Labour.checked +
theForm.LiberalDemocrats.checked) < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
function checkCheckBoxes(theForm) {
var opts = ["Conservatives","Labour","LiberalDemocrats"],
selected = 0;
for (var i = 0; i < opts.length; i++) {
if (theForm[opts[i]].checked)
selected++;
}
if (selected < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
function checkCheckBoxes(theForm) {
if(theForm.Conservatives.checked + theForm.Labour.checked + theForm.LiberalDemocrats.checked > 1)return true;
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
}
function checkCheckBoxes(theForm) {
var checkboxes = [theForm.Conservatives, theForm.Labour, theForm.LiberalDemocrats];
var checked = 0;
checkboxes.forEach(function(el){
if (el.checked) checked++;
});
if (checked < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
I keep getting the following error when I try to insert values by clicking the Next button on values that are already entered in.
Unable to get the value of the property '0': object is null or undefined.
I believe the error is happening at the last value in the array. I indicated the line below with a comment in the code. I want it to get the next value in the array but there isn't one created yet (it gets the next value just fine if the next value is not the last one in the array).
I think that is the reason it's throwing an object null. However, I can't seem to check for the null/undefined and set it using statements such as result[count+1][0] == undefined because it doesn't work! It always throws an error no matter what I do.
Some help would be much appreciated.
Test case:
Insert a value in text box 1 and text box 2
Click Next
Click Previous (in order to edit the values inserted above)
Change the values in the text boxes to something else
Click Next -- error happens
Code:
<html>
<head>
<script type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var result = new Array();
var count = 0;
var input1 = new Array();
var input2 = new Array();
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
</script>
<li>text 1</li>
<input type="text" id="txt1"/>
<br>
<li>text 2</li>
<input type="text" id="txt2"/>
<br>
<input type="button" id="btn" value="next" onclick="move('next')" />
<input type="button" id="btnprevious" value="previous" onclick="move('prev')" />
<br>
<input type="text" id="txtresult"/>
</body>
</html>
You can add a check like this:
if (typeof result[count++] === "undefined") { /* do or do not */ };
Right before:
document.getElementById("txt1").value = result[count++][0];
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
if( result[ ++count ] ) // this checks for undefined
{
document.getElementById("txt1").value = result[count][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count][1];
}
else
{
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count--; // decrement counter
}
}catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
why do you do count++ in these 2 lines?
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
seems like interpreter first increment the count and then try to get item of result which is undefined...
as i undestand pressing previous must "set cursor" to previous vaues so you can change previously entered values... in this case you shouldn't increment counter in these lines.. just remove ++
I don't get why you embedded the arrays three deep. I cleaned up some of the code and made the names more understandable (at least to me).
Regardless, when you were on the last value in the array, count++ didn't exist. Also, don't use count++ as this will increment your count var. Don't use ++ to simplify unless you truly know what you're doing and want to increment. Also, tricky shortcuts will confuse people trying to read your code, so try to be as explicit as possible. (There are exceptions to this statement, as in, you don't need to write for a person who has never coded before)
Here is working javascript:
var result = new Array();
var count = 0;
function move(direction) {
if(direction == 'next') {
var box1 = document.getElementById("txt1").value; //why did you wrap these as arrays?
var box2 = document.getElementById("txt2").value; //
if (result.length == count){
if (box1 == '' || box2 == '') {
alert('you need to put in a value');
} else {
result.push([box1, box2]); //why did you wrap individual numbers in arrays?
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
} else {
try{
result[count][0] = document.getElementById("txt1").value;
result[count][1] = document.getElementById("txt2").value;
if(result[count+1]) { // need this because if on last value in the array, count+1 will not exist yet
document.getElementById("txt1").value = result[count+1][0]; //do not do ++. this will increment count here. don't be tricky with ++
document.getElementById("txt2").value = result[count+1][1]; //because it will confuse others and lead to off by 1 errors
} else {
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
}
catch(err) {
alert(err.description);
}
}
count++;
}
if (direction == 'prev') {
if(count <= 0){
alert("no more elements");
} else {
var prev_val1 = result[count - 1][0];
var prev_val2 = result[count - 1][1];
document.getElementById("txt1").value = prev_val1;
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}