For example I have:
<p id = 'myp'>
I brought it for 2.545
I sold it for 1.245
I returned it for 5.4099
<p/>
<p id = 'myresult'> <p/>
Answer should be:
I brought it for 2.5
I sold it for 1.2
I returned it for 5.4
Keep the words in the paragraph while rounding the numbers.
myp.toFixed(2);
myparagraph = document.getElementByid('myp');
myparagraph.toFixed(2);
Doesn't work for my paragraph. I also tried MathRound(2); and other methods but it doesn't work. I'm still new to Javascript so I don't know what I'm doing. It is giving uncaught type error. I need to keep it in the paragraph I can't do var number1-1000 1000 times.
.toFixed() is a method of Number variables, so you need to get the numbers first. Also, rounding to one decimal point needs .toFixed(1), not .toFixed(2).
You can do something like this:
const mypEl = document.getElementById('myp');
const myresultEl = document.getElementById('myresult');
const values = mypEl.innerHTML.split(/\s/g).filter(Boolean);
values.forEach(value => {
myresultEl.innerHTML += Number(value).toFixed(1) + '\n';
});
<p id='myp'>
2.545
1.245
5.4099
</p>
<p id='myresult'>
</p>
Of course it will not
"myp" is a dom element not a number type
Instead you can use variables and add it to the DOM like so
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="myp"></div>
<script>
var number1 = 2.545;
var number2 = 6.556;
document.getElementById('myp').innerHTML += number1.toFixed(2);
document.getElementById('myp').innerHTML += "<br>";
document.getElementById('myp').innerHTML += number2.toFixed(2);
</script>
</body>
</html>
You can try splitting the content of #myp by the /n (new line character) then loop through the results, validate each item is an integer, convert to number then round down.
This is my thought process, I'll try writing a code sample when i get to my pc .
Related
I'm trying to insert a Math.random() into text so it would say "your number is" and then the number from the Math.random(). I can see that it I possible from this line of code: alert("Copied the text: " + copyText.value);. It shows you what you've copied but I cannot seem to figure out how to do that with Math.random().
function myFunction() {
var x = document.getElementById("demo")
x.innerHTML = Math.floor((Math.random() * 89999) + 10000);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random 5 digit number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p>I want it to say something before the number like 'order #' and then the random number</p>
</body>
</html>
Instead of using
x.innerHTML = Math.floor((Math.random() * 89999) + 10000);
Use a template string, like so:
function myFunction() {
var x = document.getElementById("demo")
x.innerHTML = `You generated ${Math.floor((Math.random() * 89999) + 10000)}`;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random 5 digit number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Template strings allow you to easily combine strings and JS code. You can put text in the template string as you would a normal string. You can also put JavaScript code that will be evaluated, converted to a string, and placed in the template string by enclosing it in ${...}. Template strings are ver powerful and can be used to do much more than the simple example I showed above. I suggest you read the documentation about them I linked above.
Alternatively, you could just concatenate strings by using the + operator. Here's an example
x.innerHTML = "You generated " + Math.floor((Math.random() * 89999) + 10000).toString();
Both have the same effect, but template strings are more powerful and are a best practice whenever possible.
I am trying to get a better hang of doing this and have been playing around with strings. What I am trying to do is collect a user input as a string and manipulate it so that when I display the text, whatever they wrote would be first displayed in all lower case, then all uppercase, then all of the text divided into its own line.
So, the output would be like this if I enter: This is an example
this is an example
THIS IS AN EXAMPLE
This
is
an
example
I feel like this is supposed to be a lot easier than it looks, but I am trying to do an all lowercase so far, but cannot get that to work so far (as well as the other two parts). I think that if I get the lowercase right, I just repeat the same thing for uppercase and splitting it.
<button onclick="myFunction()">Try it</button>
<p id="test"></p>
<script>
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML =
test.toLowerCase;
document.getElementById("test").innerHTML =
test.toUpperCase;
document.getElementById("test").innerHTML =
test.split("\n");
}
}
</script>
The above is what I am playing with so far, I get undefined when I click the button to test it. Can someone help me edit this?
functions are invoked using ()
your variable is person not test
you want to split on space not \n
you want to ADD to test innerHTML, not replace it each time
to get line breaks in HTML, use <br> tag
I've gone for code that assigns innerHTML once, as this is more performant than adding to it a bit at a time - of course, with such a simple example there's no perceived difference, however I thought I should mention why I chose to use this odd methodology
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML = [
person.toLowerCase(),
person.toUpperCase(),
person.split(" ").join('<br>')
].join("<br>");
}
}
<button onclick="myFunction()">Try it</button>
<p id="test"></p>
You may want to split the string into words first and use join() function with <br /> tags to render them into multiple lines of words.
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML +=
person.toLowerCase() + "<br />";
document.getElementById("test").innerHTML +=
person.toUpperCase() + "<br />";
document.getElementById("test").innerHTML +=
person.split(' ').join('<br />');
}
}
I can't find why I'm receiving a NaN for printing a number out with javascript.
The following code I use is repeated elsewhere on the website and works fine.
The URL in question is: http://all-american-gold10.mybigcommerce.com/us-silver-eagles/
My code is as follows:
function setCheckPrice() {
$('.NormalPrice').each(function(key, val) {
var price = $(val).html().replace('$', '').replace(',', '');
var newPrice = parseInt(price) * .03;
var setPrice = Math.floor(price - newPrice);
var credit = '<small style="font-size: 20px !important;"> - credit card price</small>';
var check = '<p><em class="new-price">$' + setPrice +'<small style="font-size: 20px !important;"> - check price</small></em></p>';
$(val).append(credit);
$(val).prepend(check);
})
};
setCheckPrice();
My code takes a number found by a specific class name, does some math and spits in back out with some extra html to go along with it. I've tried to switch the ways I've outputted the code with append, prepend, before & after, but none seem to work? Any reason why this is acting so strange?
The price variable has additional html in it. You should consider having separate elements with a class that contains just the value that you need, and nothing else. As a quick fix, this change:
var price = $(val).val().replace('$', '').replace(',', '').replace(" ","");
get's me a value of 490 for price on that page, which is what you're looking for.
looking to have the user click the button and have the fortune be selecting randomly and shown on the screen with random numbers from 1-100 underneath them. but i can't seem to get everything to display. :(
<script type = "text/javascript">
var quotes = new Array(16) // Add your quotes below
quotes[0]="Your talents will be recognized and suitably rewarded.";
quotes[1]="He who hurries cannot walk with dignity.";
quotes[2]="Your success in life must be earned with earnest efforts.";
quotes[3]="You love peace.";
quotes[4]="A friend asks only for your time and not your money.";
quotes[5]="You will soon inherit a piece of land.";
quotes[6]="Your luck is about to change.";
quotes[7]="Things will soon go your way.";
quotes[8]="He who stands on toilet is high on pot.";
quotes[8]="Everybody is ignorant, only on different subjects.";
quotes[9]="Fortune favors the brave.";
quotes[10]="There is nothing permanent except change.";
quotes[11]="You haven't failed until you give up.";
quotes[12]="Your ability to juggle many tasks will take you far.";
quotes[13]="Broke is only temporary; poor is a state of mind.";
quotes[14]="Begin nothing until you have considered how it is finished.";
quotes[15]="A huge fortune at home is not as good as money in use.";
function showFortune() {
var space = (' ') // Spacer for between numbers
var rand_inta = Math.floor(Math.random()*100); // Get first number
var rand_intb = Math.floor(Math.random()*100); // Get second number
var rand_intc = Math.floor(Math.random()*100); // Get third number
var rand_intd = Math.floor(Math.random()*100); // Get fourth number
var rand_inte = Math.floor(Math.random()*100); // Get fifth number
var rand_int = Math.floor(Math.random()*16); // Get a number for picking the quote
document.getElementById(fortuneArea).innerHTML=(quotes[rand_int]); // Put the quote in the box
}
</script>
<form action="">
<input type="button" value="Show my fortune!" onclick= "showFortune();" />
</form>
<div id="fortuneArea"></div>
document.getElementById('fortuneArea').innerHTML=(quotes[rand_int]);
Just add single quotes to id name....
I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci
You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.