I have a code which is intended to create 3 buttons (with JavaScript) and on each one of them I'm adding an event listener for click event. All of the buttons will execute the same function when it's clicked which is the mathProb() [I know it doesn't make much sense but I just want to experiment with things].
mathProb() function needs 3 arguments:
firstNumber which is the first operand.
secondNumber which is the second operand
operationSign which is the operation to be performed between the two operands
Here's the mathProb function (I put the function in the HTML head element):
function mathProb(firstNumber, secondNumber, operationSign){
switch(operationSign){
case "+":
var sum = (firstNumber + secondNumber).toFixed(2);
document.writeln("The sum of [" + firstNumber + " + " + secondNumber + "] is " + sum + " (adjusted to 2 decimal places)");
break;
case "-":
var subtract = (firstNumber - secondNumber).toFixed(2);
document.writeln("The subtraction of [" + firstNumber + " - " + secondNumber + "] is " + subtract + " (adjusted to 2 decimal places)");
break;
case "*":
var multiplication = (firstNumber * secondNumber).toFixed(2);
document.writeln("The multiplication of [" + firstNumber + " X " + secondNumber + "] is " + multiplication + " (adjusted to 2 decimal places)");
break;
case "/":
var division = (firstNumber / secondNumber).toFixed(2);
document.writeln("[" + firstNumber + " divided by " + secondNumber + "] is " + division + " (adjusted to 2 decimal places)");
break;
default:
document.writeln("You did not specify the operation sign, no operation could be performed between the two numbers!");
}
}
Now I'm planning to use the prompt() method to get the 3 arguments which will be used by the function, therefore the JavaScript code I put in the body element looks like this:
//create all the mathematical buttons
var addButton = document.createElement("input");
var subtractButton = document.createElement("input");
var multiplyButton = document.createElement("input");
var divideButton = document.createElement("input");
addButton.type = "button";
subtractButton.type = "button";
multiplyButton.type = "button";
divideButton.type = "button";
var firstNumber = parseFloat(prompt("Please enter the first number"));
var secondNumber = parseFloat(prompt("Please enter the second number"));
var operationSign = prompt("Please enter the operation sign you wish to perform on the two numbers");
//add a click event listener to all of the buttons
addButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
subtractButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
multiplyButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
divideButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
//add all the buttons to the body of the document
document.body.appendChild(addButton);
document.body.appendChild(subtractButton);
document.body.appendChild(multiplyButton);
document.body.appendChild(divideButton);
I realised that I haven't added any "value" to the buttons so I won't be able to differentiate them right now
My problem is that, once I run my code, I got the 3 prompts which will ask me for the firstNumber, the secondNumber, and the operationSign. However, for some reason, it seems like mathProb() function was executed 4 times Without ME CLICKING ON ANY OF THE BUTTONS
Here's what happened when I put 2 as the firstNumber, 3 as the secondNumber and + as operationSign:
http://imgur.com/a/APFbf
See what I'm saying? I have no idea what happened here and I can't seem to figure out what's wrong with the code either (I'm very inexperienced when it comes to javascript/html/css).
.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
Should look like:
.addEventListener("click", function(evt) {
mathProb(firstNumber,secondNumber,operationSign);
});
If You want to deliver function to argument (without execution) use functionName without ().
Example:
var someFunctionWithFunctionInArgument = function(fun) {
fun(1);
};
var superFunction = function(num) {
alert(num);
};
someFunctionWithFunctionInArgument(superFunction); // alert 1
someFunctionWithFunctionInArgument(superFunction(2)); // alert 2 and error becouse fun is not a function now
You are going too complex.
You can have this simple solution
function operate(val1,op,val2){
switch(op){
case '+' : return val1+val2; break;
case '-' : return val1-val2; break;
case '*' : return val1*val2; break;
case '/' : return val1/val2; break;
default : return 0; break;
}
}
var start = document.createElement('button');
start.innerHTML="START";
start.addEventListener('click',function(){
var result=operate(parseInt(prompt("first val")),prompt("Operator"),parseInt(prompt("Second val")));
console.log(result);
});
document.body.appendChild(start);
<body></body>
Or even more simple
var button = document.createElement('button');
button.innerHTML="START";
button.addEventListener('click',function(){
var val1=parseInt(prompt("First Val"));
var op=prompt("Operator");
var val2=parseInt(prompt("Second Val"));
console.log(eval(val1+op+val2));
});
document.body.appendChild(button);
<body></body>
Even more simple
function start(){
console.log(eval(prompt("Enter expression : "))); // like 10+5
}
function startWithTest(){
var exp=prompt("Enter expression : ");
if(/^\d+[+-\/*]{1}\d+$/.test(exp)){
console.log(eval(exp));
}
}
<body><button onclick="start();">START</button> With validating : <button onclick="startWithTest();">START With Test</button></body>
Related
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I am a beginner, working on a beginner problem but need some help
I am trying to write my own tip calculator app but I result in NaN.
I am sure it is an easy fix but I don't see what the problem is yet. My code is below. Can someone tell me what I am doing wrong that results in my finalCost resulting in NaN instead of billAmount + tipTotal?
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());
So close! You just missed passing the values into your final calculation method.
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
You could also remove the parameters and just use the "global" values in calculating
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost() {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());
There's another catch; setting float values directly from a prompt() doesn't ensure float values (treated as string by default), so wrap your prompt() functions in a parseFloat() function:
var billAmount = parseFloat(prompt('What is your total bill?'));
var tipAmount = parseFloat(prompt('How much do you want to tip'));
if(isNaN(billAmount) || isNaN(tipAmount)){
alert("Bill amount or Tip is Invalid");
} else {
console.log("This bill is " + billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
}
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
This should validate that billAmount and tipAmount values are floats, and prevent further execution if they aren't.
I want to have a user's input auto fill the punctuation of a phone number to look like this (xxx) xxx-xxxx. I have written an example jfiddle here but it breaks when filling in the last 4 digits of the phone number.
$("#phone").on("change keyup paste", function () {
var output;
var input = $("#phone").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 4);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#phone").val(output);
});
HTMl:
<input id='phone'></input>
I realize this post is older but i found it quite useful and made some minor modifications to enhance it for all telephone fields and to allow for deleting characters if the user makes a mistake.
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
<input type="tel" placeholder="(XXX) XXX-XXXX" />
When you're getting the pre code from the number, you're trying to get the index of 4, instead of four digits. So change that, and it should start working:
var pre = input.substr(3, 3);
If you don't want the dynamic filling, the other posted answers might be useful.
Regular expressions are your friend.
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}
Accepts: 404-555-1234, 4045551234, (404) 555-1234, etc.
Returns: (404) 555-1234
If you started to use regexp, why dont you go whole way through. Below the code that filter input value and convert it to your look.
Beware, this code only for value that contains only digits. You could block any other types via plugins or your own code. (jquery.numeric plugin is a good choice)
jquery
$(document).on('change', '.js-phone-number', function() {
var
$this = $(this),
number = $this.val();
number = number.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
$this.val(number);
});
You are fetching variable pre as substring of length 4 and then checking it for it is less than or equal to 3. So, basically your last else if block will never be true.
Change var pre = input.substr(3,3);
Your code will work fine.
I am trying to take the data from "create_name()" and write the outcome to the
<p id="name"> </p>
updating the variable name to show the new version.
however I am a bit lost in honesty and instead it returns "undefined" as the name.
the code obviously gets to this part and then fails:
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}
You can see the code for the entire section I am trying to make work here.
I hope I explained clearly enough.
Any Questions? feel free to ask, all help is appreciated!
init(); // lets start the inital func
function init(){ // Do some asking shit
var name = prompt('hello, what is your name?'); // ask for the name
document.write('<p id="name">hello ' + name + ' </p>');
document.write('<p id="user" >1 - create a username</p>');
document.write('<p id ="play" >2 - Play Quiz<p>');
document.write('<p id="reload">3 - quit and reload<p>');
Writedata(name); // tell our witer to write the name
}
function menu_function() {
var choice = prompt("hello " + name + " please select an option from the list to your left");
switch (choice) {
case "1": opt1_function(); break;
case "2": opt2_function(); break;
case "3": reload_method(); break;
default: menu_function(); break;
}
}
menu_function();
function opt1_function() {
alert(name + " you have selected option 1");
create_name();
}
function create_name() {
var forename = prompt("what is your forename?");
var surname = prompt("what is your surname?");
var username = alert("hello " + forename + " " + surname);
var string1 = forename.substring(0 , 1);
var create_name = alert(string1 + surname);
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}
stop assigning alert() function return values to variables, alert() has no return value look at this alert definition
change this line
var create_name = alert(string1 + surname);
to
alert(string1 + surname);
var create_name = string1 + surname;
Changed the data within the create_name() function to this:
function create_name() {
var forename = prompt("what is your forename?");
var surname = prompt("what is your surname?");
var username = alert("hello " + forename + " " + surname);
var string1 = forename.substring(0 , 1);
var create_name = string1 + surname;
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}
and now it works!
I know that $("#SendingType").val(2) sets the value of the select to 2.
So, why does this goes to else??
$(function () {
$("#calculate").click(function () {
var result = $("#SendingType").val();
var day1 = eval(result) + 3;
var day2 = eval(result) + 10;
var day3 = eval(result) + 2;
if ($("#SendingType").val(2)) {
$("#result").text(day1 + " and " + day2 + " days.");
} else {
$("#result").text(day1 + " and " + day3 + " days.");
}
});
});
I am aware that this is not correct way to code if statement.
SOLVED: Thank you Jason and Juhana. The code does not go to else, I thought it would because the value of the select influences the if result. Always if but with different results because of the new select value.
FIDDLE
Looks to me like it runs the true branch regardless:
http://jsfiddle.net/tMwRV/
Which makes sense. You are setting the value to 2, not checking the value. The statement $("#SendingType").val(2) returns a jQuery object, which is "truthy".