Javascript multiconverter - javascript

I have this 3 functions (multiconverter) in javascript, but i can´t figure it out why i can´t make the program to display the result.
function WhichConversion () {
var answer = window.prompt( " Welcome to the Mutliconverter! What do you want to convert? ( Dollars, Francs, Knots");
if (answer == "Dollars", "Knots", "Francs"){
return true;
} else {
return false;
}
}
function AskForValue () {
var answer = window.prompt( " Enter a Value to Convert")
return answer;
}
while (WhichConversion()) {
var ConversionType = WhichConversion();
var ConversionValue = AskForValue();
var resultMessage = " The result is ";
var result = 0;
if (ConversionType == "Dollars"){
resultMessage += DollarstoEuros(Number(ConversionValue))
.toString();
}else if (ConversionType == "Francs"){
resultMessage += SwissFrancsToEuros(Number(ConversionValue))
.toString();
}else if (ConversionType == "Knots"){
resultMessage += KnotstoKph(Number(ConversionValue))
.toString();
}else{
resultMessage = " Pay attention! That conversion is not supported.";
}
}
console.log(resultMessage);

The if statement to check for which conversion to use only has one check answer == "Dollars". To make the script work for other values you will need to create multiple checks:
if (answer == "Dollars" || answer == "Knots" || answer == "Francs"){
For an working example check the code below:
var currentCurrency = '';
function WhichConversion () {
var answer = window.prompt( " Welcome to the Mutliconverter! What do you want to convert? ( Dollars, Francs, Knots");
currentCurrency = answer;
return answer !== null
}
function DollarstoEuros(value){
return value * 12;
}
function AskForValue () {
var answer = window.prompt( " Enter a Value to Convert")
return answer;
}
while (WhichConversion()) {
var ConversionValue = AskForValue();
var result = 0;
var resultMessage = " The result is ";
if (currentCurrency == "Dollars"){
resultMessage += DollarstoEuros(Number(ConversionValue))
.toString();
}else if (currentCurrency == "Francs"){
resultMessage += SwissFrancsToEuros(Number(ConversionValue))
.toString();
}else if (currentCurrency == "Knots"){
resultMessage += KnotstoKph(Number(ConversionValue))
.toString();
}else{
resultMessage = " Pay attention! That conversion is not supported.";
}
console.log(resultMessage);
}

Related

Why does Javascript give me a uncaught type null error?

I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

Translating jQuery to javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to SO and to JS. I want to translate this code to pure JS but I'm really struggling. May someone help me please?
$(document).ready(function(){
var displayFix = function(num) {
if (num.length > 9) {
total.text(num.substr(0,9));
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = $(".display");
total.text("0");
$(".numbers span").not(".clear, .dot").click(function(){
number += $(this).text();
total.text(number);
displayFix(number);
});
$(".dot").click(function() {
if ( number.length == 0)
{ number = "0.";
} else {
number += $(this).text();
total.text(number);
displayFix(number);
};
});
$(".operators span").not(".igual").click(function(){
operator = $(this).text();
newNumber = number;
number = "";
total.text("0");
});
$(".clear").click(function(){
number = "";
total.text("0");
newNumber = "";
});
$(".igual").click(function(){
if (operator === "+"){
number = (parseFloat(newNumber,10) + parseFloat(number,10)).toString(10);
} else if (operator === "-"){
number = (parseFloat(newNumber,10) - parseFloat(number,10)).toString(10);
} else if (operator === "/"){
number = (parseFloat(newNumber,10) / parseFloat(number,10)).toString(10);
} else if (operator === "*"){
number = (parseFloat(newNumber,10) * parseFloat(number,10)).toString(10);
}
total.text(number);
displayFix(number);
number = "";
newNumber = "";
});
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode === 49) {
$("#num1").click();
} else if (keycode === 50) {
$("#num2").click();
} else if (keycode === 51) {
$("#num3").click();
}
});
});
I suppose I can replace the following lines:
var total = $(".display") with var total = document.querySelector(".display")
total.text("0") with total.innerHTML="0"
$(".dot").click(function() { with document.querySelector(".dot").onclick = function() {
Also, the browser I'm using is a updated Chrome and I don't need it to support other browsers.
youmightnotneedjquery is your friend.
You'll see that you can define your own replacement for jQuery.ready():
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
Then you'll need to get used to do without jQuery wrapper, which means dealing with array indexes and possibly empty results. So for instance document.querySelector(".dot").onclick = function() { is not going to be enough, you want to do
var dots = document.querySelector(".dot");
for(var i=0; i<dots.length; i++ ){
dots[i].onclick = function() { ... }
}
Finally, you need to discard elements manually since you have no jQuery .not():
var operators = document.querySelector(".operators span");
for(var i=0; i<operators.length; i++ ){
var operator = operators[i];
if(operator.className.indexOf("igual") < 0){
//do stuff
}else{
//don't
}
}
Note: you may want to use document.getElementById() and document.getElementsByClassName when your selector is just an id or a class.
Hope this short guidance is enough for you to start.
The Javascript equivalent will almost look like this for your jquery code,
(function() {
var displayFix = function(num) {
if (num.length > 9) {
total.innerHTML = num.substr(0, 9);
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = document.getElementsByClassName("display");
total.innerHTML = "0";
var sel1 = document.querySelector(".numbers span");
for (var i = sel1.length; i--;) {
if (sel1[i].className != 'clear' && sel1[i].className != 'dot') {
var arg = sel1[i].innerHTML;
sel1[i].onclick = function(arg) {
return function() {
number += arg;
total.innerHTML = number;
displayFix(number);
};
};
}
}
var sel2 = document.querySelector(".dot");
sel2.onclick = function() {
if (number.length == 0) {
number = "0.";
} else {
number += sel2.innerHTML;
total.innerHTML = number;
displayFix(number);
};
};
var sel3 = document.querySelector(".operators span");
for (var i = sel3.length; i--;) {
if (sel3[i].className != 'igual') {
var arg = sel3[i].innerHTML;
sel3[i].onclick = function(arg) {
return function() {
operator = arg;
newNumber = number;
number = "";
total.innerHTML = "0";
};
};
}
}
document.querySelector(".clear").onclick = function() {
number = "";
total.innerHTML = "0";
newNumber = "";
};
document.querySelector(".igual").onclick = function() {
if (operator === "+") {
number = (parseFloat(newNumber, 10) + parseFloat(number, 10)).toString(10);
} else if (operator === "-") {
number = (parseFloat(newNumber, 10) - parseFloat(number, 10)).toString(10);
} else if (operator === "/") {
number = (parseFloat(newNumber, 10) / parseFloat(number, 10)).toString(10);
} else if (operator === "*") {
number = (parseFloat(newNumber, 10) * parseFloat(number, 10)).toString(10);
}
total.innerHTML = number;
displayFix(number);
number = "";
newNumber = "";
};
document.querySelector(".igual").onkeypress = function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
var elm = "";
if (keycode === 49) {
elm = document.getElementById("num1");
elm.onclick.apply(elm);
} else if (keycode === 50) {
elm = document.getElementById("num2");
elm.onclick.apply(elm);
} else if (keycode === 51) {
elm = document.getElementById("num3");
elm.onclick.apply(elm);
}
};
})();
Disclaimer: The code is just converted to the JavaScript equivalent, not tested with any values.

four repeating letters check javascript, spam detection

Is there a a "smarter" way to do this? This works but I imagine has something to do with for loops, what if I was checking for 20 repeating characters?
What happens if javascript is disabled?
Is there an easier way to check for "sensical" posts instead of say aldjfalkfja;lfjaklfjlkfj how would I filter that out without storing a library of words and comparing the string to those?
function counter(){
this.value = 0;
}
var count = new counter();
function updatecount(fnc){
fnc.value = count.value + 1;
}
function charbank1(){
this.value = "";
}
var cb1 = new charbank1();
function insertchar1(fnc){
fnc.value = cb1.value + String.fromCharCode(keynum);
}
function charbank2(){
this.value = "";
}
var cb2 = new charbank2();
function insertchar2(fnc){
fnc.value = cb2.value + String.fromCharCode(keynum);
}
function charbank3(){
this.value = "";
}
var cb3 = new charbank3();
function insertchar3(fnc){
fnc.value = cb3.value + String.fromCharCode(keynum);
}
function charbank4(){
this.value = "";
}
var cb4 = new charbank4();
function insertchar1(fnc){
fnc.value = cb4.value + String.fromCharCode(keynum);
}
function repeatingcharcheck(){
if(count.value < 4){
if(count.value == 1){
insertchar1(cb1);
}
if(count.value == 2){
insertchar2(cb2);
}
if(count.value == 3){
insertchar3(cb3);
}
if(count.value == 4){
insertchar4(cb4);
}
}else{
if(cb1.value == cb2.value == cb3.value == cb4.value){
alert('four letters in a row is not allowed');
window.location.replace('somewhere.com');
}
}
}

Javascript code broken

This is my first attempt at a little more complex code structure. The thing is my IDE says it technically works , jsfiddle says it doesn't, it actually initializes only the two confirm functions that I declared "confirmUserName();" and "confirmFullName();"
Can someone explain why i did such a horrible job.
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList); v
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if(list.length == 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = usrName;
return list;
} else if(i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery; /
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm == true) {
return startRide;
} else {
return fullnameQuery;
}
}
if(username == undefined) {
usernameQuery = function() {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function() {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if(fullname == undefined) {
fullnameQuery = function() {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function() {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();
There is a lot wrong with the code you posted -- I'll just take one chunk:
function confirmUserName() {
// The return value of `confirm` is ignored.
confirm("Is " + username + " your first choice?");
// confirmUserName is the name of your function.
// You sould be using `===` instead of `==`
// Or, not comparing against true at all.
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
Fixed function:
function confirmUserName() {
var res = confirm("Is " + username + " your first choice?");
if (res) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
It does not throw Errors with this, but I dont know in which situation you want your code to be implemented and what it should do, I hope this is what you need:
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList);
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if (list.length === 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if (list[i] === undefined) {
list[i] = usrName;
return list;
} else if (i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName === true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery;
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm === true) {
return startRide;
} else {
return fullnameQuery;
}
}
if (username === undefined) {
usernameQuery = function () {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function () {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if (fullname === undefined) {
fullnameQuery = function () {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function () {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

Categories

Resources