Javascript if value is 8,11,18 change "a" to "an" - javascript

I have a field that reads your lawn takes a ___ hour shower. It is calculated by the square footage input. When the value of this field equals 8,11,or 18. I would like it to read "an ____ hour shower." How would this be made possible?
http://jsfiddle.net/on6c360o/
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var g = document.getElementById("g");
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
b.innerHTML = a.value * .62;
g.innerHTML = Math.round(a.value * .0103);
}
<div class="mobile" style="text-align:center">
<h2>Lawn Square Footage</h2>
<input id="a" onkeypress="return isNumberKey(event)" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />
<h2>Water Usage</h2>
<h2 id="b">___</h2>
<h2>Gallons per day</h2>
<h2>Your lawn takes <span id="g">___</span> hour showers</h2>
</div>

You can use a ternary operator to say if hours is 8, 11, or 18 then display an else display a.
var hours = Math.round(a.value * .0103);
g.innerHTML = (hours === 8 || hours === 11 || hours === 18 ? 'an' : 'a') + ' ' + hours;
Here's an example http://jsfiddle.net/bmec3tad/

You could perform an if check when changing the HTML contents like so:
function calculate() {
b.innerHTML = a.value * .62;
var gVal = Math.round(a.value * .0103);
g.innerHTML = gVal + ([8, 11, 18].indexOf(gVal) == -1 ? "a" : "an");
}

Related

How to save multiple user inputs into new variables

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

update val input unchanged on first hit, works on next hit

i just modified simple dinamically onChange code and added some input text below select option. theres 3 input text under it, soon after finished some modification im try it running. then why 3rd input text unchanged on first hit, it work only on next hit.
let say we pick a date : 17/08/1945 (datepicker inputtext)
1rst inputfield show only name of day :Friday
2nd inputfield returning value month : August
3rd inputfield date written in words : seventeen august one thousand nine hundred and forty-five
i know that doesn't sound like a very useful way to display a date in english, but here in Indonesia, writing the date in a word usually used for credit agreements or agreements handover and required by law
I'm making a small application and on a menu provides a feature to print a letter of agreement, automatically. that's why I need a date written in words.snippet and jsfiddle been replaced using the international language.
$( function() {
$( "#pickyDate" ).datepicker({format: "dd/mm/yyyy"});
daylocal = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu' ];
monthlocal = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni','Juli','Agustus','September','Oktober','November','Desember' ];
$('#pickyDate').datepicker()
.on("change", function () {
var today = new Date($('#pickyDate').datepicker('getDate'));
var date = today.getDate();
var daysnumber = today.getDay();
var monthnumber = today.getMonth();
var years = today.getFullYear();
numbers = $('#dateinword').val();
var number = new Array('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0');
var words = new Array('','Satu','Dua','Tiga','Empat','Lima','Enam','Tujuh','Delapan','Sembilan');/*1 to 9 */
var level = new Array('','Ribu','Juta','Milyar','Triliun'); /*hundred,thousand,billion,trillion */
var length_numbers = numbers.length;
/* long test numbers */
if (length_numbers > 15) {
sentences = "Out of Limit";
return sentences;
}
/* get numbers set to array */
for (i = 1; i <= length_numbers; i++) {
number[i] = numbers.substr(-(i),1);
}
i = 1;
j = 0;
sentences = "";
/* iteration array number */
while (i <= length_numbers) {
subsentences = "";
words1 = "";
words2 = "";
words3 = "";
/* hundred */
if (number[i+2] != "0") {
if (number[i+2] == "1") {
words1 = "Seratus"; /*Seratus mean One hundred */
} else {
words1 = words[number[i+2]] + " Ratus"; /* Ratus mean hundred */
}
}
/* tens or dozen */
if (number[i+1] != "0") {
if (number[i+1] == "1") {
if (number[i] == "0") {
words2 = "Sepuluh"; /* sepuluh mean ten */
} else if (number[i] == "1") {
words2 = "Sebelas"; /* sebelas mean eleven */
} else {
words2 = words[number[i]] + " Belas"; /* >10 - 19 using suffix Belas */
}
} else {
words2 = words[number[i+1]] + " Puluh"; /* puluh is suffix like ty in english [20,30,40,...90] */
}
}
/* single number */
if (number[i] != "0") {
if (number[i+1] != "1") {
words3 = words[number[i]];
}
}
/* zero cheking, add level */
if ((number[i] != "0") || (number[i+1] != "0") || (number[i+2] != "0")) {
subsentences = words1+" "+words2+" "+words3+" "+level[j]+" ";
}
/* join var sentences (as one blok 3 digit 000) into var sentences */
sentences = subsentences + sentences;
i = i + 3;
j = j + 1;
}
/* replace Satu Ribu(one thousand) will be Seribu if needed */
if ((number[5] == "0") && (number[6] == "0")) {
sentences = sentences.replace("Satu Ribu","Seribu"); /* Ribu = thousand we use prefix se for one */
}
//return sentences;
//alert(local[today.getDay()]);
//alert(kalimat);
$('#daypk').val(daylocal[today.getDay()]);
$('#dateinword').val(date);
$('#worddate').val(sentences);
//document.getElementById("terbilang").innerHTML=kalimat;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="specify the date of the loan agreement" name="pickyDate" id="pickyDate" />
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="name of the day" name="daypk" id="daypk" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="dateinword" name="dateinword" id="dateinword" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="will be dd/mm/yy in word" name="worddate" id="worddate" disabled/>
</div>
</div>
</div>
</div>
https://jsfiddle.net/ariowishnu/vLeqLkj6/1/
Unfortunately I can say that I don't speak Indonesian, and so it's difficult to tell what exactly your code intends to do and why your logic might be structured the way it is. However, I might be able to give you a few pointers based on my testing of your code that might change the results for the first change event:
You set some variable bilangan = $('#nominal').val() towards the beginning of your event handler. This will always be the empty string '' on the first iteration, because nothing has been inputted into that field yet.
You base your while loop off of a variable panjang_bilangan = bilangan.length. That loop will never run the first time, because bilangan is the empty string and thus has a length of zero.
Your third input (the one that is having the error) seems to be updated entirely based off of a variable called kaLimat. From what I can tell, the only places where this variable is updated to include some meaningful value are inside your while loop, and that is why for the first event kaLimat ends up being empty, and your <input id="terbilang"> doesn't change.
Edit: I think I found a solution
The problem was with numbers = $('#dateinwords').val(). That line should be:
var numbers = date + ''
...which sets numbers to the string-equivalent of the selected day of the month ("date").
I also prefixed a few of your variables with var when you set them initially so that they don't leak into the global namespace.
I did not take a look at the correctness of your algorithm to turn dates into strings, since I don't fully understand the rules by which that should be done in Indonesian. Let me know if the snippet doesn't function as intended.
Snippet:
$(function() {
daylocal = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
monthlocal = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$('#pickyDate').datepicker({ format: 'dd/mm/yyyy' })
.on("change", function() {
var today = new Date($('#pickyDate').datepicker('getDate'));
var date = today.getDate();
var daysnumber = today.getDay();
var monthnumber = today.getMonth();
var years = today.getFullYear();
var numbers = date + ''
var number = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
var words = new Array('', 'Satu', 'Dua', 'Tiga', 'Empat', 'Lima', 'Enam', 'Tujuh', 'Delapan', 'Sembilan'); /*1 to 9 */
var level = new Array('', 'Ribu', 'Juta', 'Milyar', 'Triliun'); /*hundred,thousand,billion,trillion */
var length_numbers = numbers.length;
/* long test numbers */
if (length_numbers > 15) {
var sentences = "Out of Limit";
return sentences;
}
/* get numbers set to array */
for (i = 1; i <= length_numbers; i++) {
number[i] = numbers.substr(-(i), 1);
}
i = 1;
j = 0;
sentences = "";
/* iteration array number */
while (i <= length_numbers) {
var subsentences = "";
words1 = "";
words2 = "";
words3 = "";
/* hundred */
if (number[i + 2] != "0") {
if (number[i + 2] == "1") {
words1 = "Seratus"; /*Seratus mean One hundred */
} else {
words1 = words[number[i + 2]] + " Ratus"; /* Ratus mean hundred */
}
}
/* tens or dozen */
if (number[i + 1] != "0") {
if (number[i + 1] == "1") {
if (number[i] == "0") {
words2 = "Sepuluh"; /* sepuluh mean ten */
} else if (number[i] == "1") {
words2 = "Sebelas"; /* sebelas mean eleven */
} else {
words2 = words[number[i]] + " Belas"; /* >10 - 19 using suffix Belas */
}
} else {
words2 = words[number[i + 1]] + " Puluh"; /* puluh is suffix like ty in english [20,30,40,...90] */
}
}
/* single number */
if (number[i] != "0") {
if (number[i + 1] != "1") {
words3 = words[number[i]];
}
}
/* zero cheking, add level */
if ((number[i] != "0") || (number[i + 1] != "0") || (number[i + 2] != "0")) {
subsentences = words1 + " " + words2 + " " + words3 + " " + level[j] + " ";
}
/* join var sentences (as one blok 3 digit 000) into var sentences */
sentences = subsentences + sentences;
i = i + 3;
j = j + 1;
}
/* replace Satu Ribu(one thousand) will be Seribu if needed */
if ((number[5] == "0") && (number[6] == "0")) {
sentences = sentences.replace("Satu Ribu", "Seribu"); /* Ribu = thousand we use prefix se for one */
}
//return sentences;
//alert(local[today.getDay()]);
//alert(kalimat);
$('#daypk').val(daylocal[today.getDay()]);
$('#dateinword').val(date);
$('#worddate').val(sentences);
//document.getElementById("terbilang").innerHTML=kalimat;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="specify the date of the loan agreement" name="pickyDate" id="pickyDate" />
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="name of the day" name="daypk" id="daypk" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="dateinword" name="dateinword" id="dateinword" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="will be dd/mm/yy in word" name="worddate" id="worddate" disabled/>
</div>
</div>
</div>
</div>

Round up the values in my calculator script & add commas separator for the value

I have the problem. My JS knowledge & experience is very poor so I can't solve it without your help. I have the following code for my simple calculator and I want to add some code for this:
If I enter a number such as 10010 into the calculator, I get $7.508 back. How can I make it so that there are always 2 digits past the period and round it up? In this case, it would be best if it showed $7.51 instead of $7.508. If I entered 4,000 it shows "$3" but can it say "$3.00"?
Thank you in advance!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="How many likes?" style="height: 50px;width: 360px;color: #222;border-radius: 5px;border: 1px #85c9e3 solid;font-size: 18px;" type="text" id="likecount" />
<p style="font-family: 'Montserrat', sans-serif; padding: 20px 0px; font-weight: bold; color: #222; ">Pricing: <b><span style="color: #004f04;"> $</span><span id="output" style="color: #004f04;"></span></b></p>
<script type="text/javascript">function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}
// number format set to en-US e.g (from 1500 to 1,500)
var numFormat = new Intl.NumberFormat("en-US");
$('#likecount').keyup(function(e){
// if a '.' is pressed
if($(this).val().endsWith('.')) {
return;
}
// if input value is empty then assign '0' else the original value
var inputVal = $(this).val() === ''?'0':$(this).val();
inputVal = parseFloat(inputVal.replace(/[$|,]/g, ''));
var price = priceCalculation($(this).val());
var total = inputVal * price;
var formatted = numFormat.format(inputVal) // set format to input
$(this).val(formatted); // display the formatted input back
$('#output').text(numFormat.format(total)); // display the total price
});
</script>
You can make total to be 2 decimal places by adding total.toFixed(2). I have added it for you.
var total = (inputVal * price).toFixed(2); Read more about .toFixed at MDN
Check it out in the DEMO below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="How many likes?" style="height: 50px;width: 360px;color: #222;border-radius: 5px;border: 1px #85c9e3 solid;font-size: 18px;" type="text" id="likecount" />
<p style="font-family: 'Montserrat', sans-serif; padding: 20px 0px; font-weight: bold; color: #222; ">Pricing: <b><span style="color: #004f04;"> $</span><span id="output" style="color: #004f04;"></span></b></p>
<script type="text/javascript">function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}
// number format set to en-US e.g (from 1500 to 1,500)
var numFormat = new Intl.NumberFormat("en-US");
$('#likecount').keyup(function(e){
// if a '.' is pressed
if($(this).val().endsWith('.')) {
return;
}
// if input value is empty then assign '0' else the original value
var inputVal = $(this).val() === ''?'0':$(this).val();
inputVal = parseFloat(inputVal.replace(/[$|,]/g, ''));
var price = priceCalculation($(this).val());
var total = (inputVal * price);
total = (Math.round(total * 100) / 100).toFixed(2);
var formatted = numFormat.format(inputVal) // set format to input
$(this).val(formatted); // display the formatted input back
$('#output').text((total)); // display the total price
});
</script>
Intl.NumberFormat accepts an options parameter that allows you to influence style.
From your example, it seems like you could use:
var numFormat = new Intl.NumberFormat("en-US", { style: 'currency', currency: 'USD' });
Note that this will also add the currency symbol (such as here, a dollar sign). If you really just want to control the rounding, you may set minimumFractionDigits and maximumFractionDigits instead:
var numFormat = new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 });
Important line :
var total = (inputVal * price).toFixed(2);
Working Demo
Try below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="How many likes?" style="height: 50px;width: 360px;color: #222;border-radius: 5px;border: 1px #85c9e3 solid;font-size: 18px;" type="text" id="likecount" />
<p style="font-family: 'Montserrat', sans-serif; padding: 20px 0px; font-weight: bold; color: #222; ">Pricing: <b><span style="color: #004f04;"> $</span><span id="output" style="color: #004f04;"></span></b></p>
<script type="text/javascript">function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}
// number format set to en-US e.g (from 1500 to 1,500)
var numFormat = new Intl.NumberFormat("en-US");
$('#likecount').keyup(function(e){
// if a '.' is pressed
if($(this).val().endsWith('.')) {
return;
}
// if input value is empty then assign '0' else the original value
var inputVal = $(this).val() === ''?'0':$(this).val();
inputVal = parseFloat(inputVal.replace(/[$|,]/g, ''));
var price = priceCalculation($(this).val());
var total = (inputVal * price);
total = (Math.round(total * 100) / 100).toFixed(2);
var formatted = numFormat.format(inputVal) // set format to input
$(this).val(formatted); // display the formatted input back
$('#output').text(total); // display the total price
});
</script>

Javascript: Currency converter

Im new in javascript and I'm trying to make a simple currency converter, it is working fine when I select "£Pound" "£Pound" or "£Pound" "R$Real" but when I select "R$Real" "R$Real" runs the "Pound" "R$Real" calculation.
I spent hours trying to figure this out (very frustrating).
How to fix it? Is there another way to do it? (also tried using " if " and " else if " same issue). Thanks!
Here`s the HTML:
<label>Amount:</label>
<input type="text" id="amount" />
<label>From:</label>
<select id="select1">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<label>To:</label>
<select id="select2">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<input type="button" onClick="calculation()" value="calculate" />
<div id="result"></div>
Here`s the JS:
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch((currency1)&&(currency2)){
case "pound":
case "pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound":
case "real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}}
To fix your JS do the following:
The issue is that your switch would compute to a single string, and you are using fall-through switch statements, jsFiddle to demonstrate what I mean.
Switch Statement Documentation for JavaScript
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch (currency1 + ' ' + currency2) {
case "pound pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}
}
Use the below to display the number and then just put the symbol in front, as this code will add commas and separators in the right spots, including negative.
Format number to currency:
function formatCurrency(num, precision) {
//identify '(123)' as a negative number
if (typeof num == 'string' && num.toString().indexOf('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && precision === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
if (num === '' || (num === '-' && precision === -1)) {
return;
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (precision >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(precision); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
if ((hasDecimals && precision == -1) || precision > 0) {
num += '.' + decimals;
}
// format symbol/negative
var format = isPositive ? '%s%n' : '(%s%n)';
var money = format.replace(/%s/g, '$');
money = money.replace(/%n/g, num);
return money;
}
console.log(formatCurrency(12002031203120, 2))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body{
background:linear-gradient(3150deg,#7458ff,#a48afc);
background-size: cover;
height: 800px;
display: flex;
align-items: center;
justify-content:center;
}
.col-md-8{
background-color: rgb(183, 170, 170);
padding: 10px 24px;
border-radius: 20px;
width: 490px;
}
.form-group{
width: 100%;
display: flex;
}
input{
width:95%;
color:aliceblue;
height: 40px;
font-size: 1em;
margin: 0.2em 0;
border-radius: 10px;
border: none;
background: #676666;
outline: none;
padding: 0.1em;
}
select{
width: 50%;
height:40px;
font-size: 30px;
cursor: pointer;
background: #039cfb;
outline: none;
color: black;
padding: 0 1em;
border-radius: 10px;
border: none;
}
</style>
</head>
<body>
<div class="col-md-6 well">
<h3 class="text-primary">Javascript - Simple Currency Converter</h3>
<hr style="border-top:1px dotted #ccc;">
<div class="col-md-8">
<h4>Converter</h4>
<hr style="border-top:1px groovy #ccc;"/>
<div class="form-group">
<select onchange="Currency(); Calculate()" class="form-control" id="converter" style="width:30%;">
<option value="Dollar">Dollar</option>
<option value="Pound">Pound</option>
<option value="Euro">Euro</option>
<option value="Yen">Yen</option>
<option value="Yuan">Yuan</option>
</select>
<br />
<input type="number" oninput="Calculate()" class="form-control" id="value1"/>
</div>
<br /><br />
<div class="form-group">
<label>Pak Rupee:</label>
<input type="number" class="form-control" id="value2" disabled="disabled"/>
</div>
</div>
</div>
<script>
function Currency(){
y = document.getElementById("converter").value;
return y;
}
function Calculate(){
y = Currency();
x = document.getElementById("value1").value;
if(x == ""){
document.getElementById("value2").value = "";
}else{
switch(y){
case "Dollar":
document.getElementById("value2").value = x * 215.99;
break;
case "Pound":
document.getElementById("value2").value = x * 72.39;
break;
case "Euro":
document.getElementById("value2").value = x * 63.84;
break;
case "Yen":
document.getElementById("value2").value = x * 0.49;
break;
case "Yuan":
document.getElementById("value2").value = x * 8.20;
break;
}
}
}
</script>
</body>
</html>

Javascript calculator value

Below I have Javascript code (a calculator). Also I have several inputs (<input name="roip" value="xxxx" class="input c2" type="text">). What should I write in value (value"xxxx" )?
This is my HTML:
<input name="amount" value="xxxx" onchange="calculate()" type="text">
<input name="roip" value="xxxx" class="input c2" type="text">
<input name="ret" value="xxxx" class="input c2" type="text">
And my Javascript:
function calculate() {
c = new Array(1, 10, 500, 104, 1, 501, 2000, 105, 1, 2001, 5000, 106, 1, 5001, );
a = document.calc.amount.value
p = 0;
for (i = 0; i < c.length; i += 4) {
if (c[i] == document.calc.plan.selectedIndex + 1) {
if ((a >= c[i + 1]) && (a <= c[i + 2])) p = c[i + 3];
}
}
if (p == 0) {
p = '-';
a = '-';
} else {
a = a * p / 100;
}
document.calc.roip.value = p;
document.calc.ret.value = a;
}
calculate();
Write whatever you think is a good default/example value or don't supply a default. Alternatively you could have a message like "type amount here" which is cleared when the user first clicks the textbox.
are you asking how to display the results in the inputs?
you don't need to assign a value to your inputs, because the js function is getting the values ( document.getValueByName('amount').value )
you can use :
to display the value zero as default value

Categories