javascript append appearing twice - javascript

Here's my problem I have this javascript
if (exchRate != "") {
function roundthecon() {
var value = Math.round(exchRate*Math.pow(10,2)) / Math.pow(10,2);
$('.tablenotes > p > strong ').append(value);
}
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// When the document is loaded..
$(document).ready(function(){
// Grab an array of the table cells
$('.evenprop table tr td:not(.title)').each(function(){
// Calculate the pound price
var v_euro = $(this).html();
if (v_euro != "N/A") {
var v_euro = v_euro.replace(/,/g,'');
var v_euro = v_euro.replace(/\u20AC/g, '');
var v_euro = v_euro.replace(/£/g, '');
var v_pound = Math.round(v_euro / exchRate);
v_pound = addCommas(v_pound);
// Create a new span element for the pound
// Insert it at the end of the table cell
if (exchRate == <%= Session("xch_dollar") %>) {
$(this).prepend("$");
}
if (exchRate == <%= Session("xch_ntl") %>) {
$(this).prepend("X");
}
if (exchRate == <%= Session("xch_euro") %>) {
$(this).append("€");
}
var o_span = $('<span/>').html(' <span style="font-weight:normal;" id="exchRate">(£' + v_pound + ')</span>');
$(this).append(o_span);
}
});
});
}
And this is my html in the page
<div class="tablenotes">
<p><span class="tariffnote">Weekly price in Euros.</span> £ in brackets are approximate sterling equivalent based on <strong>£1 =
<script type="text/javascript">roundthecon()</script><noscript><%= Session("xch_euro") %></noscript>€</strong> </p>
</div>
And the exchRate = 1.1986 for some reason my code is showing this.
<div class="tablenotes">
<p><span class="tariffnote">Weekly price in Euros.</span> £ in brackets are approximate sterling equivalent based on <strong>£1 =
1.2<noscript>1.1986</noscript>€1.2</strong> </p>
</div>
It is rounding the exchRate as it should but it is placing it in twice
Anyone got any ideas?
Thanks
Jamie

I got around the issue by doing this
$(document).ready(function(){
var value = Math.round(exchRate*Math.pow(10,2)) / Math.pow(10,2);
$('.tablenotes > p > strong ').html("£1 = " + value + "€");
});
It replaces the whole html rather than appending

Related

jQuery number format for HTML input number with dynamic decimals

I've seen a lot of similar threads or library but I haven't found one I need.
I have preexisting code with many input[type=number] in the forms. I need to format the number value to local format when form is viewed at first load or when cursor/pointer is out of focus (onblur), and unformat the number to raw input when onfocus or when the form is submitted. The format are dot as separator and comma as decimal. The decimal numbers are dynamic, some don't have decimals, some have 2 or 4, or in other words, the decimal format is only shown when the number has decimal. And when a field doesn't have any value, still displays an empty string ("") not zero (0). A field that has 0 value still displays a 0.
Example:
//Number is 1400.45
//Document ready: 1.400,45
//Onfocus: 1400.45
//Onblur: 1.400,45
//Onsubmit value send by PHP page load: 1400.45
Is there any way to do this or jQuery/javascript library for this?
I don't think there is a library for such a specialized solution you are looking for but you can do it on your own.
That's the idea:
String.prototype.replaceLast = function(find, replace) {
var index = this.lastIndexOf(find);
if (index >= 0) {
return this.substring(0, index) + replace + this.substring(index + find.length);
}
return this.toString();
};
let transformValue = function(value) {
value = parseFloat(value);
value = parseInt(value).toLocaleString() + '.' + parseInt(value.toString().split('.')[1] || '0');
value = value.replace(',', '.');
value = value.replaceLast('.', ',');
return value;
};
let form = document.querySelector('#myForm');
window.addEventListener('load', function() {
let inputs = form.querySelectorAll('input[type="text"]');
for (let i = 0; i < inputs.length; i++) {
let input = inputs[i];
input.value = transformValue(input.value);
input.onfocus = function() {
this.value = this.value.replaceAll('.', '').replace(',', '.');
};
input.onblur = function() {
this.value = transformValue(this.value);
};
}
});
form.onsubmit = function() {
let inputs = form.querySelectorAll('input[type="text"]');
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = inputs[i].value.replaceAll('.', '').replace(',', '.'); }
for (let i = 0; i < inputs.length; i++) {
alert('submitted value ' + inputs[i].value);
}
};
#myForm {
display: flex;
flex-direction: column;
}
#myForm input {
outline: none;
border: 1px solid #000;
border-radius: 3px;
margin: 5px 0;
padding: 3px 7px;
}
<form id="myForm">
<input type="text" value="1400.45">
<input type="text" value="1401.45">
<input type="text" value="1402.45">
<input type="submit">
</form>
The below solution is totally dynamic, as wherever you want to put decimal position.
var num;
$(document).ready(function(){
num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings));
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split(".");
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});
$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});
$(".nums").blur(function(){
num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings));
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split(".");
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});
$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});
$(".form1").submit(function(){
var numz2=num;
$(".nums").val(numz2);
$(".form1").submit();
});
function pad (str, max) {
str = str.toString();
return str.length < max ? pad(str+"0", max) : str;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form1" action="submit.php" method="post">
<input type="text" name="num" class="nums" value="1.40045">
<input type="submit">
</form>

How to use multiplate onkeyup input?

I have this input, I want use 2 onkeyup in one input, How use it?
I want sepret my number 3 number with comma and I want my input value of a factor of 10 too.
For example, if the user enters the number 100214, the user will immediately see the number 10021 (No decimal) in span result and see the number 100,214 in input.
function separateNum(value, input) {
var nStr = value + '';
nStr = nStr.replace(/\,/g, "");
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
if (input !== undefined) {
input.value = x1 + x2;
} else {
return x1 + x2;
}
}
function onInputChange(e) {
const span = document.getElementById('result');
span.innerHTML = Math.floor(e.value / 10);
}
<input type="text" onkeyup="onInputChange(this); separateNum(this.value,this);">
<span id='result'>please enter number</span>
function test2(value, input) {
var nStr = value + '';
nStr = nStr.replace(/\,/g, "");
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
console.log(x1)
}
if (input !== undefined) {
input.value = x1 + x2;
} else {
return x3 + x2;
}
}
function test1(e) {
const span = document.getElementById('result');
e.value = e.value.replace(/,/gi,'')
span.innerHTML = Math.floor(e.value / 10);
}
<input type="text" onkeyup="test1(this); test2(this.value,this);"/>
<div id='result'></div>
change this:
<input type="text" onkeyup="onInputChange(this)" onkeyup="separateNum(this.value,this);">
to:
<input type="text" onkeyup="onInputChange(this); separateNum(this.value,this);">
You should not be using inline HTML event attributes in today's world. Inline event attributes like onXyz where how we "wired" up event handling functions to events before we had standards 25+ years ago. Using this technique today "works", but introduces shortcomings and, in some cases, bigger problems.
Instead, follow modern standards and use .addEventListener() separately in JavaScript, which provides a more robust mechanism for event handling registrations (and de-registrations). In your case, you would just register two handlers for the same event and they will be invoked in the order that you registered them:
// Get a reference to the HTML element
const input = document.querySelector("input");
// Register event handlers
input.addEventListener("keyup", foo1);
input.addEventListener("keyup", foo2);
function foo1(event){
console.log("foo1 detected key up after " + event.key + " was pressed and now the input is: " + this.value);
}
function foo2(event){
console.log("foo2 detected key up after " + event.key + " was pressed and now the input is: " + this.value);
}
<input type="text">

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

Create form for function Html

This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>

Find the string occurence and wrap it with a span

<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div>cout<<"hey";cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
I wanted to find cout using regex, something like /cout[^;]*;/ and then wrap it with a span.
<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div><span id="group">cout<<"hey";</span>cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
How will i find the regex occurence and the wrap it with a span? Anyone please?
UPDATE: I inserted cin>>x; after cout, cin shouldn't be wrapped.
I want to use something like this
text.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>');
But i dont know how to apply it in DOM. anyone?
BUG for cin>> and cout<<, they cant be wrap until ; http://jsfiddle.net/3N4AE/11/
This is how you would apply the regex to your DOM using jQuery:
$('#wrapper div').filter(':contains("cout")').each(function () {
$(this).html($(this).text().replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
Demo fiddle
update Regex way
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.html(txt.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
DEMO
var x =$('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('').append('<span id="group">'+txt+'</span>');
updated after OP updated question
DEMO
var x = $('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
update
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
});
updated after koala-dev comment
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else if ($.trim(val) != '') {
x.append(val + ';');
}
});
});
This should help
var pattern = /cout[^;]*;/;
var txt = $('#wrapper').find('div:nth-child(2)').text();
var el = $('#wrapper').find('div:nth-child(2)');
$(el).text("").append('<span id="group">' + txt + '</span');
jsfiddle

Categories

Resources