jquery - number formatting issue - javascript

This is my code:
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.field.js" type="text/javascript"></script>
<script src="js/jquery.calculation.js" type="text/javascript"></script>
<script>
$(function() {
$('input[name^=sum]').keyup(function() {
var sum1 = parseFloat($('input[name=sum1]').val()) || 0;
var sum2 = parseFloat($('input[name=sum2]').val()) || 0;
var sum3 = parseFloat($('input[name=sum3]').val()) || 0;
$('#c_card_amount').val(sum1*sum3/100);
$('#total_inc_charges').val((sum1*sum3/100)+sum1);
});
});
</script>
In the input fields I would like to show the numbers in 1,000.00 format.
How can I format the numbers like this? Right now after the calculation numbers sometimes gets messed up like 452.25600000001. I would like to avoid that as well. Would be nice to rule the numbers properly.
Thank you for your help.

I recommend that you use NumberFormatter. Also you can see this question.

I would recommend you to try jQuery Format as mentioned in this question: Format numbers in javascript.
Below is an example of jQuery Format:
$.format.locale({
number: {
groupingSeparator: ',',
decimalSeparator: '.'
}
});
$.format.number(1000, '#,###.00'); // result: 1,000.00
$.format.number(452.25600000001, '#,###.00'); // result: 452.26

I would recommend you to use javascipt instead of jQuery. While jQuery made life more easy but don't forget that jQuery can be too large and your user have to load it on page while browsing.
Read this article for your answer http://www.mredkj.com/javascript/numberFormat.html

Related

MathJax equation containing multiple summations with index

Background:
Here is how I am including the MathJax library in my page:
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Problem:
The MathJax string (that I believe) will display what I want:
$$\sum_{s=1}^{1000} p_s \sum_{c=1}^{4} x_c$$
The closest MathJax string that I can get to work (display correctly):
$$\sum_{s=1}^{1000} p_s \sum_c^{4} x_c$$
As part of debugging, I have simplified the second summation down to 'x_c' but it still does not work. This leads me to believe that the problem is caused by the second summation index definition. When I try to add the 'c=1' bit to the second summation notation, it seems MathJax will no longer render the equation at all. This behavior seems strange since the first summation can have the defined index (e.g., 'i=1'). Any thoughts appreciated at this point.
As #Peter_Krautzberger has noted it looks like the Markdown parser has converted some text to italics. Which could be causing the issue.
The below snippet is to verify that the issue is not with MathJax.
<script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML-full&latest"></script>
$$\sum_{s=1}^{1000} p_s \sum_{c=1}^{4} x_c$$
According to https://divadnojnarg.github.io/blog/mathjax/ MathJax \sum_ does not work correctly in markdown and you have to use \sum\_.
Latex rendering errors
There are some differences with classical Latex expressions and the syntax to use in a markdown document. For example, \sum_ does not render with Hugo and you should use \sum_ instead (notice the second backslash before the underscore).
Try escaping the underscores.
Either:
$$\sum\_{s=1}^{1000} p\_s \sum\_{c=1}^{4} x\_c$$
or
$$\sum\_{s=1}^{1000} p_s \sum\_{c=1}^{4} x_c$$
Might do the trick.
There is also some additional config mentioned in the article that may be required:
<script type="text/javascript" async
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
displayMath: [['$$','$$']],
processEscapes: true,
processEnvironments: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
TeX: { equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js"] }
}
});
MathJax.Hub.Queue(function() {
// https://github.com/mojombo/jekyll/issues/199
var all = MathJax.Hub.getAllJax(), i;
for(i = 0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
MathJax.Hub.Config({
// Autonumbering by mathjax
TeX: { equationNumbers: { autoNumber: "AMS" } }
});
</script>

MathJax event just before a latex expression is typset

I have a MathJax sample at Demo sample, which works as expected. All it does is typset the latex expressions within a div having an id of mathDiv.
I need to execute some custom logic when the third latex expression is about to be typset i.e. when ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ is going to be typset.
Question
Can I execute some custom JavaScript just before the above latex expression get typset by MathJax and if yes, then how would I do it?
I was thinking there might be some event model associated with MathJax typesetting, but couldn't find any in the docs.
The same demo sample code is as below.
<h2>Math Test</h2>
<div id="mathDiv">1. Solve for x $$X^2-1 = 8$$.
<br>2. Evaluate the following limit: $$\lim_{x \rightarrow b}{ (x-10) }$$
<br>3. Is ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ ?
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
$(document).ready(function() {
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "mathDiv"]);
});
</script>
There are signals for when math is typeset (see this example), though the signals for HTML-CSS output are a bit more complicate than for the other output formats.
But there is another approach that may work better for you. You can register a preprocessor that will run after the tex2jax preprocessor has located the math in the page, and that will put your wrapper around the math at that point. Then when the math is typeset, it will be inside the wrapper automatically.
Here is one example for that:
<style>
#math0 {color:red}
#math1 {color:blue}
#math2 {color:green; font-size: 200%}
#math3 {color:purple; font-size: 75%}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
MathJax.Hub.Register.PreProcessor(function (element) {
//
// Get the math scripts created by tex2jax
//
var math = element.querySelectorAll('script[type^="math/tex"]');
//
// Loop through them in reverse (since this
// is a live list)
//
for (var i = math.length - 1; i >= 0; i--) {
//
// Get the script and any preview that preceeds it
//
var script = math[i];
var preview = script.previousSibling;
if (preview && preview.className !== 'MathJax_Preview') preview = null;
//
// Create the wrapper span and give it an id
// (If you will be typesetting more than once,
// you will need to keep a global id number
// and use that rather than i)
//
var span = document.createElement('span');
span.id = 'math'+i;
//
// Insert the wrapper in place of the script
// and append the preview and script to
// the wrapper.
//
script.parentNode.replaceChild(span,script);
if (preview) span.append(preview);
span.append(script);
}
},50); // use priority 50 so it follows the standard MathJax preprocessors
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS_CHTML-full"></script>
<h2>Math Test</h2>
<div id="mathDiv">1. Solve for x $$X^2-1 = 8$$.
<br>2. Evaluate the following limit: $$\lim_{x \rightarrow b}{ (x-10) }$$
<br>3. Is ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ ?
</div>
Here, the wrappers are styled to add color, and to scale the third and fourth expressions.
I hope the comments make it clear what is happening. This preprocessor will be run any time MathJax.Hub.Typeset() is called, so you can use that as normal.
Note that if the math is in the page initially, as it is here, there is no need to queue the Typeset() call by hand (as MathJax will typeset the page initially). If you are dynamically modifying the page, then you will need to do that.

numeral.js live formatting

I would like to live format an input box with Numeral.js.
I tried something like this.
$('#exchangeInputFirst').keyup(function () {
//eur formatting
numeral.language('sk');
$('#exchangeInputFirst').val(numeral($('#exchangeInputFirst').val()).format('0,0.00$');
//to HUF format $('#exchangeInputSecond').val($('#exchangeInputFirst').val()*$('#first').html());
numeral.language('hu');
var string = numeral($('#exchangeInputSecond').val()).format('0,0.00$');
$('#exchangeInputSecond').val(string);
});
The second function is working perfectly (to HUF format), but the first not.
I think you are missing the numeral language file:
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
I cannot reproduce your situation unless I do not include the languages js file. Try your example and hit a key on the first input box:
var a = false;
$('#exchangeInputFirst, #exchangeInputSecond').click(function () {
$(this).caret(0);
});
$('#exchangeInputFirst, #exchangeInputSecond').keyup(function(){
if(a == false){
$(this).val('');
a = true
} else {
numeral.language($(this).data('language'));
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
}
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/numeral.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
<script src="http://zikro.gr/dbg/html/jquery.caret/dist/jquery.caret-1.5.2.min.js"></script>
<input type="text" data-language="sk" id="exchangeInputFirst">
<input type="text" data-language="hu" id="exchangeInputSecond">
UPDATE
You also have a problem with the cursor position. You can solve this by using this jQuery plugin acdvorak/jquery.caret to set the caret position to the beggining of the input each time characters are typed like this:
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
Also, I have included the language in input's data like data-language="sk" and now you can read it directly in the keyup event like this:
numeral.language($(this).data('language'));
See my updated snippet. It should now works as you want.

jQuery event handlers does not work?

var imgadd = $("<img/>",{
src:"../img/Koala.jpg",
alt:"Koala",
id:"koala",
click:function(){$(this).css("opacity","50%");},
mouseenter:function(){$(this).css("hight","200px")}
})
$("body").append(imgadd);
why does it not work?I got a little pizzled...
The code is structurally correct, the issue is that you made two typo's.
opacity takes a value between 0 and 1, not a percentage.
height was misspelled.
Here's code that will work:
var imgadd = $("<img/>",{
src:"http://idordt.nl/wp-content/uploads/2014/06/wk-koala.jpg",
alt:"Koala",
id:"koala",
click:function(){$(this).css("opacity","0.5");},
mouseenter:function(){$(this).css("height","200px")}
})
$("body").append(imgadd);
And a jsFiddle: http://jsfiddle.net/jaredcrowe/3fvht8s2/
Change the values either 0 to 1
var imgadd = $("<img/>",{
src:"http://idordt.nl/wp-content/uploads/2014/06/wk-koala.jpg",
alt:"Koala",
id:"koala",
click:function(){alert("hello");$(this).css("opacity","0.2");},
mouseenter:function(){$(this).css("height","200px")}
})
$("body").append(imgadd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

How to migrate a .change function from jQuery to plain Javascript

I'm not a JS expert but i think what i'm trying to do is pretty simple (at least in jQuery)
I've got 3 select
<select id="faq" class="onchance_fill">...</select>
<select id="pages" class="onchance_fill">...</select>
<select id="faq" class="onchance_fill">...</select>
and an input (it's a tinyMCE one in advlink plugin)
<input type="text" onchange="selectByValue(this.form,'linklisthref',this.value);" value="" class="mceFocus" name="href" id="href" style="width: 260px;">
I want that each time i change a value in one of the 3 select, that this value of the option, will be placed in the input.
In Jquery, it would be something like :
$('.ajax_onchance_fill').change(function() {
data = $('.ajax_onchance_fill').val();
$('#href').text(data);
});
But i can't use it. So what is the equivalent in plain Javascript ?
Thanks
I would advice you keep using Jquery as it speeds up this kind of thing but in pure JavaScript i think what you want looks something like this...
<script type="text/javascript">
function load() {
var elements = document.getElementsByClassName('onchance_fill');
for(e in elements){
elements[e].onchange = function(){
document.getElementById('href').value = this.value;
}
}
}
</script>
document.getElementsByClassName("ajax_onchance_fill").onchange = function() {
getElementById('href').value = this.options[this.selectedIndex].text;
};
Though I am not sure exactly if it'll work since getElementsByClassName returns more than 1 element.
Try this:
$('.ajax_onchance_fill').change(function() {
var data = $(this).val();
$('#mytextboxid').val(data);
});
Okay, so I realize this thread is well over 8 years old, so this answer isn't so much for the OP (who probably figured it out long ago) as it is for someone else who might be curious about this particular topic.
All that said, here's a relatively simple and reliable way you could pull it off in vanilla JS:
/**
* Since we need to listen to all three ajax_onchance_fill elements,
* we'll use event delegation.
*
*/
const targetLink = document.getElementById('href');
document.addEventListener('change', function(e) {
if (!!Element.prototype.matches) { // Let's make sure that matches method is supported...
if (e.target.matches('.ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
} else { // and if not, we'll just use classList.contains...
if (e.target.classList.contains('ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
}
});

Categories

Resources