<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
I just want the value £123 to show, need correct Javascipt to "trim" the number and not round it down or up. I've seen a few ways on here but none that target .class name, in my case .numTxt
If somebody can do me a quick fiddle I would be most appreciative!
You can use .text() call back function to modify the old text with new text:
$('li.numTxt').text(function(i,val){
return val.split(".")[0];
});
Working Demo
Here you are:
alert(document.querySelector('li').innerText.replace(/\.\d*/,''));
Hope this help.
You can do this easily with split()
var str = "£123.99"
var res = str.split(".");
//res is now an array consisting of "£123" and "99"
Working Example:
$('button').click(function(){
var str = $('#inp').val();
var res = str.split(".");
$('#output').html(res[0]);
});
input, button, div { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp" value="£123.99" />
<button>Split At Decimal</button>
<div id="output"></div>
Just use this Regex /\.\d+/:
$.fn.trimDecimal = function(){
$(this).text(function(a, text){
return text.replace(/\.\d+/,"")
})
}
$(".numTxt").trimDecimal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£83.45</li>
To truncate a decimal number, you can do it in this way:
var num = "123.99";
num = +num | 0;
console.log(num)
Related
Hi I would like to do a Word Count in my RTE (Rich Text Editor) with javascript can also use with jquery. But it should not count the html tags and repeating white spaces.
Sample Text:
<p>11 22 33</p><p>44</p>5<br></div>
The javascript should display 5 only.
Is there any javascript code for this and that is also fast to calculate the Word Count?
Thanks!
Try something like this:
You get the html in the div then you remove all tags and replace them with spaces. You remove (trim) all left and right spaces and finally you split the string into an array. The length is your answer.
var cont = $("#content").html();
cont = cont.replace(/<[^>]*>/g," ");
cont = cont.replace(/\s+/g, ' ');
cont = cont.trim();
var n = cont.split(" ").length
alert(n);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<p>11 22 33</p><p>44</p>5<br></div>
var words = [];
function getWords(elements) {
elements.contents().each(function() {
if ($(this).contents().length > 0) return getWords($(this));
if ($(this).text()) words = words.concat($(this).text().split(" "));
})
}
getWords($('<div>').html('<p>11 22 33</p><p>44</p>5<br></div>'));
console.log(words,words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do something tricky by using jQuery by creating an element with the content.
var str = '<p>11 22 33</p><p>44</p>5<br></div>';
var len = 0;
// create a temporary jQuery object with the content
$('<div/>', {
html: str
})
// get al child nodes including text node
.contents()
// iterate over the elements
.each(function() {
// now get number or words using match and add
len += (this.textContent.match(/[\w\d]+/g) || '').length;
});
console.log(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use Countable.js for live word counting, although it doesn't ignore HTML tags.
Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();
I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/
I am having this text in text area.
{color:#c91d1d}Hello{color}
when it is submitted, i want the text between {} tags to be shown in color specified inside {} tag with color:
how can i do so in javascript
use javascript built in function to extract color code
var colorValue = str.substring(7, 7);
it extract 7 characters from 7th position.
now change the color using:
document.getElementById("myH2").style.color = colorValue;
I hope this will work
You can use a regex like
$('#input').on('input', function() {
$('#result').html(this.value.replace(/\{color:(.*?)\}(.*?)((\{color\})|$)/g, '<span style="color:$1">$2</span>'));
}).triggerHandler('input');
textarea {
width: 100%;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="input">{color:#c91d1d}Hello{color} - {color:green}hi{color}</textarea>
<div id="result"></div>
Arun is right, and if you just need to get "Hello" from "{color:#c91d1d}Hello{color}" string you can do it like this
var justtext="{color:#c91d1d}Hello{color}".match(/\{.*\}(.*)\{.*\}/)[1];
For full replacement of text in textarea here's the code. Suppose textarea has id attribute "textarea1", change it with your id.
var textwithcolor =$("#textarea1").text();
var justtext=textwithcolor.match(/\{.*\}(.*)\{.*\}/)[1];
$("#textarea1").text(justtext);
this is how it can be done
No need to use regular expressions.
try this
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("{color}") > -1) {
newstr = newstr.replace("{color}", "</div>");
}
while (newstr.indexOf("{color:") > -1) {
newstr = newstr.replace("{color:", "<div style='color:");
newstr = newstr.replace("}", "'>");
}
document.getElementById("t").innerHTML = newstr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">{color:#c91d1d}Hello{color}
{color:red}How{color} {color:yellow}are{color} {color:green}you{color}
</div>
I need to be able to add a decimal from input to a decimal in a div. Here's my code below. Right now, it's just concatenating the two number next to each other. Thanks.
EDITED: Working code
<div id="addme">5.01</div>
<input type="text" id="anumber" value="">
<button id="add">Add Number to div</button>
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
//alert(number);
$('#addme').html(function(i, val) {
return (parseFloat(val) + number).toFixed(2);
});
});
Old Non-Working Code Below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="addme">5.01</div>
<input type="text" id="anumber" value="" />
<button id="add">Add Number to div</button>
<script type="text/javascript">
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number==''){
var number=0;
}
//alert(number);
$('#addme').html(function(i, val) {return val*1+number });
});
</script>
Since you're dealing with decimal numbers, use parseFloat():
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat(val) + number;
});
});
http://jsfiddle.net/mblase75/47t7x/
UPDATE
Since you might introduce floating-point math errors (try inputing "0.6"), you should round it to a suitable number of decimal places before returning (2 if dealing with dollars and cents; 7 or more if dealing with other measurements):
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat((parseFloat(val) + number).toFixed(9));
});
});
http://jsfiddle.net/mblase75/47t7x/1/
You should use parseInt() for this.
$('#addme').html(function(i, val) {return parseInt(val,10)+parseInt(number,10) });
Just make sure you're parsing the strings to actual numeric values.
function(i, val) {return parseFloat(val)*1+parseFloat(number) }
in your code it seem you want the sum, not concatenation
here is the code for sum, and you need to place that on a $(document).ready because your code was running before the objects were available.
$(document).ready(function() {
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number=='')
number=0;
var target=$('#addme');
target.html(1*target[0].innerHTML+1*number);
});
});
if you want concatenation just remove the 1*
To convert string to number you can use the trick with + before string value. It will convert string value to numeric. This code works fine:
$('#add').click(function() {
var number = +$('#anumber').val() || 0;
$('#addme').html(function(i, val) {
return (+val + number).toFixed(2);
});
});
DEMO: http://jsfiddle.net/K9g49/
// On the click event of #add
$('#add').on("click", function(){
// n is equal to #anumber, or 0 if #anumber is blank
var n = $('#anumber').val() || 0
// Determine new HTML content for #addme
$('#addme').html(function(i,v) {
// Return the sum of n and v floated, to two decimal places
return ( parseFloat(n) + parseFloat(v) ).toFixed(2);
});
});
Fiddle: http://jsfiddle.net/G8nka/1/