Next/Previous button throws error - javascript

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;
}

Related

Javascript Code Executes Correctly in browser but receiving multiple "Declaration or statement expected" errors at end of code in VSCODE

I am getting 9+ errors at the end of my code saying "Declaration or Statement Expected." I am pretty sure my syntax is correct but I could be wrong. The program runs fine, just wondering why I am getting these errors. The error displays in VSCODE, I don't see the error here. Here is a picture: VSCODE SCREENSHOT NOTE: IF YOU RUN THE CODE JUST TYPE 'quit' and it will exit.
let toDoList = [];
let input = prompt("What Would You Like to Do");
while (input!== 'quit'){
if (input === "new".toLowerCase())
{
let addAToDo = prompt("What Would You Like to Add?") ;
toDoList.push(addAToDo)
console.log( `${addAToDo} added to the list!`)
}
else if (input === "list".toLowerCase())
{
console.log("*********************")
for(i = 0; i < toDoList.length; i++){
console.log(`${i}:${toDoList[i]}`)
}
console.log("*********************")
}
else if (input === "delete")
{
let deletedIndex = parseInt(prompt("Which Index Would You like to Delete?"));
const deleted = toDoList.splice(deletedIndex, 1)
console.log(`${deleted} has been Deleted`)
}
input = prompt("What Would You Like to Do")
}
console.log("Ok You Quit");
Someone pointed out in your comments that the code is messy. I cleaned the code and now it is working fine.
let toDoList = [];
var input = prompt("What Would You Like to Do");
while (input != 'quit') {
if (input == "new") {
var addAToDo = prompt("What Would You Like to Add?");
toDoList.push(addAToDo);
console.log(`${addAToDo} added to the list!`);
} else if (input == "list") {
console.log("*********************");
for (i = 0; i < toDoList.length; i++) {
console.log(`${i}:${toDoList[i]}`);
}
console.log("*********************");
} else if (input == "delete") {
let deletedIndex = parseInt(prompt("Which Index Would You like to Delete?"));
const deleted = (toDoList).splice(deletedIndex, 1);
console.log(`${deleted} has been Deleted`);
} else {
void(0);
}
input = prompt("What Would You Like to Do")
}
console.log("Ok You Quit");

Javascript array push issue or loop issue

When I'm running my code I'm going into 'do' loop, then I'm entering input 'new' and then trying to add new array, but for some reason my code starting looping in if(answ == "new"). What am I doing wrong?
Here is my code:
var answ;
var arr = [];
do{
answ = prompt("What would like to do?");
if(answ == "new"){
var add = prompt("Add new todo: ");
add = arr.push(answ);
}
else if(answ == "list"){
for(var i=0; i<arr.length; ++i){
answ = answ + arr[i] + '<br>';
}
}
else if(answ == "delete"){
var choose = prompt("Which one (index)?");
delete arr[choose];
}
}while(answ !== "quit")
Don't run in browser in current form (never ending loop)
See if this helps you Mark.
there were some errors with you logic and storing values and also you were not showing the values, if what I suggest is right.
var answ;
var arr = [];
do {
answ = prompt("What would like to do?");
if (answ == "new") {
var add = prompt("Add new todo: ");
arr.push(add);
} else if (answ == "list") {
var output = '';
for (var i = 0; i < arr.length; ++i) {
output += arr[i] + '\r\n';
}
alert('listing:' + '\r\n' + output );
} else if (answ == "delete") {
var choose = prompt("Which one (index)?");
arr.splice(choose,1);
} else {
if(answ !== "quit")
alert('option invalid!');
}
} while (answ !== "quit")

Javascript break/continue statement

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>

Only JavaScript Dynamic Array Field Validation

I think so there is a problem with for statement??
Adjusted code again, but not alert popup is all the time even if all the input fields got values?
Hello I am trying to validate a dynamic array of fields on a form:
<form onsubmit="return checkReq();">
<input value="" type="hidden" name="slider[]" id=""/>
</form>
with the following JavaScript, but it doesn't work? Could you tell me please what I am doing wrong.
<script language="javascript">
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
</script>
I think this might help.
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
You always return after the first loop, so it doesn't go through each element (and thus redundant), is this intended?
Try this
You are trying to compare element instead of it's value JSFIDDLE
function checkReq () {
var boxes = document.getElementsByName("slider[]");
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
alert('Problem'); return false;
}
else {return true;}
}
}

for loop getting skipped in javascript

I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");

Categories