I am trying to implement jQuery animateNumber, and I have it working like the demo just fine. However, I want to modify it so that it pulls the number from the HTML, rather than setting it in the script. I tried the following, but it just shows "NAN." What am I doing wrong?
<div class="stat-title animate-number">$16,309</div>
<script>
$('.animate-number').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = $(this).text();
value = parseInt(value);
// Set the starting text to 0
$(this).text('0');
$(this).animateNumber(
{
number: value,
},
1000
)
});
</script>
ParseInt is failing because of the $ character. Also, the comma is messing with parseInt and giving you the value 16 instead of 16309. After that, the animation seems to be working. Also, you don't necessarily have to replace it with 0 since animateNumber automatically starts from 0. Here's my work so far on JSfiddle:
http://jsfiddle.net/0m9828kn/1
$('.animate-number').each(function(){
var value = $(this).text();
value = value.substring(1, value.length);//Remove $ sign
value = value.replace(/,/g, "");//Remove all commas
value = parseInt(value);
//$(this).text("0"); //This part isn't actually necessary
$(this).animateNumber(
{
number: value
},
1000
)
});
Looks like the problem is that ParseInt is choking on the dollar sign. Then when you remove that, it only reads up to comma and animates to 16. Take them both out, and it works.
value = $(this).text().replace(/[\,\$]/g,'');
But, you'll need to include this option to get your comma back:
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator(',')
$(this).animateNumber(
{
number: value,
numberStep: comma_separator_number_step
},
1000
)
To get your dollar sign back, you could change your html to something like this:
<div>$<span class="stat-title animate-number">16,309</span></div>
Related
Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"
I'm trying to add 10% to a price field via javascript and so far i haven't been able to, and was hoping you guys would be able to help.
The field incl. currency code etc.
I did try something in this direction:
<script type="text/javascript">
$( document ).ready(function() {
var Total = $("#cashamount");
Total.val(Total.val() * 1.1);
});
</script>
But that didn't work ;(
The price field shows up like the following.
<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>
After adding the 10% to the price, it should say in this example:
<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>
Any ideas are welcome, and i would really appreciate help on this matter as i do think it's fairly simple but i'm not very well into Javascripting.
First this: (solution below)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the
.val() method returns an array containing each selected option; if no
option is selected, it returns null, jQuery docs
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method,
jQuery docs
So, one solution would be next:
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this
Here's JsFiddle
var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;
So you can create a function for this:
function updateVal(elem){
var x = elem.html(); // Fethching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
elem.html(y); // Setting the html;
}
and use it as:
$(document).ready(function(){
updateVal($("#cashamount"))
});
I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea
I'm attempting to finish up a quick form using jQuery that needs to add a 0 before a decimal point if the decimal is the first char entered in the input.
For example,
.25 would become 0.25 before the form is submitted.
However, 2.05 would stay as 2.05, and no 0 would be added.
Is there a simple function here that could help me out? I'd rather not write something long and detailed if it's not necessary.
Also, here is the input box that I am asking for help with, for reference
<input type="number" name="dailygain" id="dailygain" />
You can use parseFloat function to format float numbers.
var el = document.getElementById("dailygain");
el.value = parseFloat(el.value);
Multiply by 1 (*1) to make it numeric.
If you make it a number, it'll do it for you automatically; formatting based on your systems locale.
Example:
var x = '.25';
console.log( x*1 ); // 0.25
The same can be accomplished with a unary plus (e.g., console.log( +x ); )
Put this in a function run onsubmit.
var num=$("#dailygain").val(); //read the number from the textbox
num=num.toString(); //convert that number to a string
if (num.charAt(0)==".") //check if the string starts with a period
num="0"+num; //if so, add a 0 in front of it
$("#dailygain").val(num); //write the number back to the tb
parseFloat is probably more suited, but anyway :
$('#dailygain').on('keyup', function() {
if (this.value[0] === '.') this.value = '0'+this.value;
});
FIDDLE
$("input[name=dailygain]").keyup(function(){
var val = this.value;
if(val.charAt(0) === '.'){
this.value = ('0'+val);
}
});
http://jsbin.com/ofivun/2/edit
Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10