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")
Related
I am trying to do a pop-up warning before the sales order is saved if the exact same item is entered twice when the order is created/modified on Netsuite. However, there is no window popping up and I am not sure what is wrong with the script. Here is what I got:
function validateitem (type){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (type == 'item' && numLine > 0) {
for(var i = 0; i < numLine; i++) {
var itemSO = {};
itemSO.id = nlapiGetLineValue('item','item',i);
if (itemSO.id != null && itemSO.id !=''){
for (var j = 0; j < numLine; j++){
if(itenArr.indexOf(itemSO[i].id) === -1) {
itemArr.push(itemSO[i].id);}
else{
if (!confirm('You have entered a duplicate item for this sales order. Continue?'))
{
flag = false;
}
}
}
}
}
}
return flag;
}
Can somebody help, please?
Here is a slightly edited version:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = 1; j <= numLine; j++){
if(itemArr.indexOf(itemSO[i]) === -1) {
itemArr.push(itemSO[i]);}
else{
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
This is the complete after-edit code that works:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = i+1; j <= numLine; j++){
var itemSOplus = nlapiGetLineItemValue('item','item',j);
if(itemSO === itemSOplus) {
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
Thanks to Krypton!!
As per SuiteAnswers ID 10579, there are no paramters passed to the saveRecord client event. Therefore when your code checks the following:
if (type == 'item' && numLine > 0)
it finds that type equals undefined, so the condition is not met and the code will jump straight down to return flag which has been set to true.
Also note that in SuiteScript 1.0, line indexes start from 1 - not 0 as your code seems to assume.
EDIT - adding comment to form part of this answer:
I'd like to understand your logic behind itemSO[i] - as itemSO is not an array. Why not just compare the item from the current line of the inner loop with the current line of the outer loop and set the flag false if they match? Also, the inner loop need only start from j = i + 1 as the previous lines would have already been compared.
var game = prompt('Do you want to play?');
var i = 0;
do {
if (prompt === 'Yes');
{
var game2 = prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("You're words are: " + game2);
How do I take all the words outputted from this loop and build a string with it?
Ex: if all my words are "basketball, football, racing"
I want them to come out outputted like --> basketball football racing
Hope this helps...
var game = prompt('Do you want to play?');
var game2 = '';
var space = ' ';
var i = 0;
do {
if (prompt === 'Yes');
{
game2 = game2 + space + prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
prompt("You're words are: " + game2);
It looks like you have a few things wrong with your code. You could use the .join method if you put all of the responses into an array.
var game = prompt('Do you want to play?');
var i = 0;
var words = [];
do {
// if (prompt === 'Yes'); // this isn't doing anything
// {
words.push(prompt('Enter your word.'));
var game3 = prompt('Do you want to play again?');
// }
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("You're words are: " + words.join(' '));
To what i understood from your question, This should Work.
var game = prompt('Do you want to play?');
var i = 0;
var game2="";
do {
if (prompt === 'Yes');
{
game2 += " "+prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
console.log(game3);
console.log("You're words are: " + game2);
Basically, you are just concatenating dynamically.
Try this one
var words = [];
var i = 0;
do {
var game = prompt('Do you want to play' + ((words && words.length) ? ' again' : '') + '? (type yes to continue else exit)');
if(game && game.toLowerCase() === 'yes') {
var word = prompt('Enter your word.');
if(word) {
words.push(word);
}
}
} while (game && game.toLowerCase() === 'yes');
if(words && words.length) {
console.log("You're words are: " + words.join(', '));
} else {
console.log("no words selected!");
}
You can go with String Array:
var gameArr =[];
gameArr.push(prompt('Do you want to play?'));
var i = 0;
do {
if (prompt === 'Yes');
{
gameArr.push(prompt('Enter your word.')); // This will append new string in current string.
gameArr.push(prompt('Do you want to play again?'));// this also append the new string.
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("Your words are: " + gameArr[1]);
Let me know if you are unsure how you will get your responses from the array gameArr[].
My code is not reporting any errors no matter what I do. This is for a indexed array and I was to get an error when I prompt user to enter the list number they want to delete. It should give me an error if its not in the index or not a integer.
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
try {
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else{
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
output.innerHTML = delMessage;
}
//Return false to prevent submission:
return false;
}catch(ex){
console.log(ex.message);
}
}
simple, add the below code to beginning of try block
if((input -parseInt(input ))!=0) throw new Error('not integer');
it should do the trick.
I changed your function, please see if it is what you want:
var tasks = [1,2,3,4,5,6,7,8,9,10];
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else if (delTask == 0){
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
document.getElementById('output').innerHTML = delMessage;
} else {
throw "The value is not number or not index of array! Try again!";
}
//Return false to prevent submission:
return false;
}
try {
deleteTask();
} catch (e) {
console.log(e);
}
The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
printList = function() {
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
document.write(i + ":");
document.write(myList[i] + "<br/>");
};
document.write("<br/><br/>");
};
// initial list
var myList = new Array ();
if (myList.length === 0) {
document.write("I have " + myList.length + " item in my list. It is: <br/>");
}
else {
document.write("I have " + myList.length + " items in my list. They are: <br/>");
}
printList();
var continueAdding = "yes";
var askToContinue = "";
while (continueAdding === "yes") {
// loop
var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
switch (askUser) {
case "A": { // add an user specified item to the list
var addItem = prompt("Add something to the list");
myList.push(addItem);
printList();
break;
}
case "R": { // remove an user specified item from the list
var removeItem = prompt("what do you want to remove?");
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
break;
}
if (myList.length === 0) {
myList[0] = "Nada";
}
};
printList();
break;
}
default: {
document.write("That is not a proper choice.");
}
};
askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
if (askToContinue === "Y") {
continueAdding = "yes";
}
else {
continueAdding = "no";
}
}
Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
break;
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
}
};
if (myList.length === 0) {
myList[0] = "Nada";
}
Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.
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;
}