I am using money.js, a plugin to convert currency and am setting the content of a div like so:
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
I am trying to separate the number with commas after every three digits and have tried adding .toLocaleString to the line but couldn't get it to work.
Have been looking on here all night for different solutions such as with regex etc. but haven't found anything yet...any ideas?
This is all the code:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://cdn.rawgit.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
}
$.getJSON("http://api.fixer.io/latest", demo);
});
</script>
As it is currency, It will have .## at the end of it right?
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
Related
My javascript to get the day and time and to place it in the div is as below:
function print(message){
var div1= document.getElementById("date-and-time");
div1.innerHTML= message ;
}
function addZero(i) {
if (i < 10) {i = "0" + i;}
return i;
}
function todaysDate (){
var today= new Date();
var day= today.getDay();
var daylist=["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
var whatDayTime = "<p> Today is " + daylist[day] + ". </p>";
var hour= addZero(today.getHours());
var minute= addZero(today.getMinutes());
var second= addZero(today.getSeconds());
whatDayTime += "<p> The time is " + hour + ":" + minute+ ":" + second + ".
</p>";
return whatDayTime;
}
print(todaysDate());
HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Practice JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="date-and-time">
</div>
<script src="practice.js"></script>
</body>
I keep getting the error message" cannot set property of innerHTML to null". help? Many thanks. i am a beginner.
date-and-time is class name not id. You should add id to element,use like this,
<body>
<div class="date-and-time" id="date-and-time">
</div>
or change your function, use getElementsByClassName method, Look at this article.
function print(message){
var div1= document.getElementsByClassName("date-and-time");
div1[0].innerHTML= message ;
}
When looking for an element with an id, that element must exist. You used class instead of id.
False:
<div class="date-and-time"> </div>
Right:
<div id="date-and-time"> </div>
You need to select element by class instead of id using querySelector
Replace
var div1= document.getElementById("date-and-time");
by
var div1= document.querySelector(".date-and-time");
date-and-time is class name and you are accessing it by ID.
Either change attribute name to id or access element by class name or querySelector.
I'm new to JS and I am trying to make two random strings that were selected by using math.random() and put them into my p tag so that I could end up with something like 'Storm Breaker' or 'Castle Eater', but it seems I can only display the first name (fname) or the last name (lname). I tried to do
document.getElementById("print").innerHTML=fname,lname;
That didn't work so I also tried:
document.getElementById("print").innerHTML=fname;
document.getElementById("print").innerHTML=lname;
But as you could tell that would just change where the first name would be into the last name.
<h1 class="title">Welcome to Tom's Random Name Generator!</h1>
<button type="button" onclick="myFunction();">Generate!</button>
<p id="print"></p>
<script>
function myFunction() {
var fnamel = ['Storm','Wind','Castle','Chocolate','Savage'];
var lnamel = ['Breaker','Eater','Smasher','Killer','Fury'];
var fname = fnamel[Math.floor(Math.random()*fnamel.length)];
var lname = lnamel[Math.floor(Math.random()*lnamel.length)];
document.getElementById("print").innerHTML=fname;
}
</script>
Change like this :
document.getElementById("print").innerHTML=fname + " " + lname;
Final code :
<html>
<head>
<style>
</style>
</head>
<body>
<h1 class="title">Welcome to Tom's Random Name Generator!</h1>
<button type="button" onclick="myFunction();">Generate!</button>
<p id="print"></p>
<script>
function myFunction() {
var fnamel = ['Storm','Wind','Castle','Chocolate','Savage'];
var lnamel = ['Breaker','Eater','Smasher','Killer','Fury'];
var fname = fnamel[Math.floor(Math.random()*fnamel.length)];
var lname = lnamel[Math.floor(Math.random()*lnamel.length)];
document.getElementById("print").innerHTML=fname + " " + lname;
}
</script>
</body>
</html>
You can concatenate strings in javascript using the plus operator.
document.getElementById("print").innerHTML=fname + ' ' + lname;
I want to format this date: <div id="date">23/05/2013</div>.
First I want to split the string at the first / and have the rest in the next line. Next, I’d like to surround the first part in a <span> tag, as follows:
<div id="date">
<span>23</span>
05/2013</div>
23
05/2013
What I did:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function() {
$("#date").text().substring(0, 2) + '<br />';
});
</script>
See the JSFiddle.
But this does not work. Can someone help me with jQuery?
Using split()
Snippet :
var data =$('#date').text();
var arr = data.split('/');
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
Fiddle
When you split this string ---> 23/05/2013 on /
var myString = "23/05/2013";
var arr = myString.split('/');
you'll get an array of size 3
arr[0] --> 23
arr[1] --> 05
arr[2] --> 2013
Instead of using substring with a fixed index, you'd better use replace :
$("#date").html(function(t){
return t.replace(/^([^\/]*\/)/, '<span>$1</span><br>')
});
One advantage is that it would still work if the first / is at a different position.
Another advantage of this construct is that it would be extensible to more than one elements, for example to all those implementing a class, just by changing the selector.
Demonstration (note that I had to select jQuery in the menu in the left part of jsfiddle's window)
You should use html():
SEE DEMO
$(document).ready(function(){
$("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));
});
try
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
<div id="date">23/05/2013</div>
var arr = $('#date').text().split('/');
console.log(arr);
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date">23/05/2013</div>
use this
<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
var x = $("#date").text();
x.text(x.substring(0, 2) + '<br />'+x.substring(3));
});
</script>
Try this
$("div#date").text().trim().replace(/\W/g,'/');
DEMO
Look a regular expression
http://regexone.com/lesson/misc_meta_characters
enjoy us ;-)
var str = "How are you doing today?";
var res = str.split(" ");
Here the variable "res" is kind of array.
You can also take this explicity by declaring it as
var res[]= str.split(" ");
Now you can access the individual words of the array.
Suppose you want to access the third element of the array you can use it by indexing array elements.
var FirstElement= res[0];
Now the variable FirstElement contains the value 'How'
What i'm trying to do is taking the price of every input checked, making a sum out of it.
Here's my code
function totalSum(e) {
e.preventDefault();
var unit = $("input:checked").parent("dt").siblings("dd").find("span");
total = 0;
$.each(unit, function(index, obj){
total += parseInt($(obj).text(), 10);
});
$("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}
Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:
<dd><span class="costo">€199</span></dd>
So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it?
Thanks in advance
Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way
<body>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div id="total"></div>
<script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script>
<script>
$(document).ready(function(){
function sum() {
var prices = $("div.bla").find(".count");
total= 0;
$.each(prices, function(index, obj){
total += parseFloat($(obj).text());
});
$("#total").html('<span class="count">'+total +'</span> €');
};
});
This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!
You can just replace any non-numeric characters:
total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);
Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.
You can simply remove the unit from the text :
var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?
Or, if you want to only keep digits and + and -, do
var text = $(obj).text().replace(/[^\d\-\+]/g, '');
Change your parseInt to skip the first character.
total += parseInt($(obj).text().substring(1),10);
After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)
$("input").on("click", function() {
var j = $("input:checked");
t = 0;
$(j).each(function() {
t += parseInt(this.value, 10);
});
$("#total").html("<span>€ " + t + "</span>");
});
This is a really stupid question.
I have a javascript string variable for a name, and i want to display it where it says user like this:
"Hello, user!" --> "Hello, Chris!
Surely you could have found this answer out easily yourself :p
Put the name in a span and give it an ID
Hello <span id="name"></span>
Then set the text using getElementByID
var name = "Chris";
document.getElementById('name').innerHTML = name;
var user_name = 'Chris';
document.writeln("Hello, " + user_name);
I think document.write plus some string concatenation are what you're looking for:
var user = "Chris";
document.write("Hello, " + user + "!");
Something like this will do the trick.
var user = 'Steve';
document.write('hello ' + user);
If you need to target an element, you can use the usual methods, such as:
var user = 'Steve';
var thisOne = document.getElementById('thisOne');
thisOne.innerHTML = ('hello ' + user);
May as well throw in a jsfiddle so you can play around an experiment.
This is example of dislay string into span tag.
'+' operator uses for string concatenation.
<html>
<head>
<script>
var name = 'Chris';
var field = document.getElementById('show_string');
field.innerHTML( '"Hello, '+ name + '!"' );
</script>
</head>
<body>
<span id='show_string'></span>
</body>
</html>
You can concatenate the user's name with the rest of the string you want to display like so:
<p id="hello"></p>
<script type='text/javascript'>
var user_name = "Chris";
var hello_string = "Hello, " + user_name;
document.getElementById("hello").innerHTML = hello_string;
</script>