Javascript try and catch - javascript

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

Related

Letter decode Javascript

I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));

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")

I am writing a hangman program in java script and need help getting the word to display if the player loosed

Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.

Use jquery or javascript to add commas to disabled field

I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.

I am trying to make my input strings lower case using Dojo

I have this security question answer input field validate function where I want to make sure the string are converted to lowercase just in case a user enter a answer in caps in the first field and in small case in the second field:
validate : function(){
//check if both input fields are not blank
//if not blank, check to see if they match and send back status message
var _inputs = dojo.query("#" + this.id + " input");
var _y = ""
var _matchingValues = [];
_this = this;
for(var i = 0, len = _inputs.length; i < len; i++) {
_matchingValues.push(_inputs[i].value);
}
dojo.forEach(_matchingValues, function(arr) {
if (arr == "") {
_this.status = "incomplete";
//_this.status = "invalid";
return _this.status;
}
else if (arr != _y) {
_y = arr;
_this.status = "nomatch";
return _this.status;
}
else if (arr.length < 3){
_this.status = "short";
return _this.status;
}
else {
_this.status = "valid";
return _this.status;
}
});
},
How can this be accomplished
_matchingValues.push(_inputs[i].value);
You can change this so it only pushes the lowercase values before you perform your comparison.
_matchingValues.push(_inputs[i].value.toLowerCase());

Categories