separated numbers three to three? - javascript

How can when that typed numbers in input:text, separated them three to three and between them puting this:","?
normal number formatting
Example: typed this number in input: 45656839
result (live - online) in same input: 45,656,839
i not want use of plugin.
With respect

Demo
This should do it for you.
<input type="text" class="numeric" />
$("input:text.numeric").keyup(function(){
$val = $(this).val();
$(this).val($val.match(/[0-9]{1,3}/g).join(","))
});
EDIT
For normal number formatting, the code is a little different. There's probably a some good regex out there for this but my first thought was to reverse the string and apply the same technique. Then you reverse the string again and you have it
$("input:text.numeric").keyup(function(){
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
EDIT 2
Demo
And for future reference if anyone wants to implement this with decimal places (yeah I got carried away :P) ...
$("input:text.numeric").keyup(function(e){
if(e.which > 40 || e.which == 8) {
var num = $(this).val().match(/[0-9,]*/g)[0];
var decimalNum = $(this).val().match(/[.][0-9]*/) || "";
if(num) {
var wholeNum = num.match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
var resultNum = wholeNum + decimalNum;
$(this).val(resultNum);
}
else
{
$(this).val(num);
}
}
});

I think that masked input plugin could be a good solution. You can read more here: http://digitalbush.com/projects/masked-input-plugin/

function thousandSeparator(n,sep) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue=n+'';
if (sep === undefined) {sep=',';}
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1'+sep+'$2');
}
return sValue;
}
From: http://webdesign.onyou.ch/2010/08/04/javascript-inserting-thousand-separators/

Just do something like this (untested, should work):
$(':text').blur(function(){
var $this = $(this), val = $this.val(), newVal = ''
for (var i = 0; i < val.length; i++) {
newVal += val.charAt(i)
if (!((i + 1) % 3))
newVal += ','
}
$this.val(newVal.slice(0,-1))
})
Edit: See Joseph's answer above. His is shorter.

Related

pass $` value to associated parameter function of replace

I have an expression say
log(1,3)+4,5+max(7,8,9)
where comma is being used two ways.
1- In "log(1,3)+4,5" comma is being used in place of dot(.) or decimal sign.i.e. "log(1,3)+4,5" is equivalent to "log(1.3)+4.5".
2- In max(7,8,9) it is being used as number separator. i.e. this outcome of this is 9 ; the maximum number.
My problem is to substitute comma; which is being used as decimal separator; with decimal but this should not affect max(7,8,9). i.e. I need to convert above expression to
log(1.3)+4.5+max(7,8,9)
What I tried-
function substitute(expr) {
expr.replace(/,/g, function ($`) {
/*some processing here to decide whether comma to be substituted with dot or not.On that basis I will return either dot or comma.*/
}
But how can I pass $` value to associated function
or
Is it possible to do this in javascript.
expr.replace(/,/g,function ($`) {
if yes then how?
Your language is ambiguous.
max(8,1,8,2)
Does this return 8, 8,1 or 8,2?
Your language also doesn't look regular, so you can't parse it with a regular expression, you need the context. If something like this is allowed:
max(1,max(2,3)) // 3?
Assuming you can get rid of the ambiguity, you could write a parser to do the context detection.
This could be a solution :
function myFilter(string) {
// save all functions and signs
var functions = [];
var regExp = /[+,-]max\(([^\)]+)\)/;
matches = true;
while (matches !== null) {
var matches = regExp.exec(string);
if (matches !== null) {
functions.push(matches[0]);
string = string.replace(matches[0], '');
}
}
// replace all remaining commas with dots
string = string.replace(/,/g , ".");
for (i in functions) {
string += functions[i];
}
return string;
}
var s = '1,3+4,5+max(7,8,9)-max(2,3,5)';
var filteredString = myFilter(s);
jsFiddle Demo
This currently works with multiple max functions but only + and - signs. It could be improved with *, / and more... You will have to find the good regex.
Try the below using Javascript. Hope this helps you in logic.
DEMO HERE
var value = "log(1,3)-4,5+max(7,8,9)";
var val = '';
var splitValue, appendSym;
if (value.indexOf("+") != -1)
{
splitValue = value.split("+");
appendSym = "+";
}
else if(value.indexOf("-") != -1)
{
splitValue = value.split("-");
appendSym = "-";
}
else if(value.indexOf("*") != -1)
{
splitValue = value.split("*");
appendSym = "*";
}
else
{
splitValue = value.split("/");
appendSym = "/";
}
var length = splitValue.length;
for (var i = 0; i < length; i++) {
if (val) val += appendSym;
var strrep = splitValue[i].replace(/,/g,".");
if (splitValue[i].indexOf("max") != -1 || splitValue[i].indexOf("min") != -1)
{
val+=splitValue[i];
}
else
{
val+=strrep;
}
}
alert(val);
The output for the above code is log(1.3)-4.5+max(7,8,9)

Make input to get only numbers with two decimal places

Currently I am using following jQuery code to filter only digits:
$('#input_field').keyup(function(e) {
if (/\D/g.test(this.value)) {
this.value = this.value.replace(/\D/g, '');
}
});
But I want to get floating point numbers(upto to 2 decimal places) like this:
10.2
1.23
1000.10
Try this regex:
/^\d+(\.\d{0,2})?$/
Your JS:
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
try
toFixed(2)
eg:
var number = 2.234239;
var numberfixed=number.toFixed(2);
I think you have to use typing interval, because keyup is to quick and the regex don't approve something like this 0.
var typingTimer;
var doneTypingInterval = 1000;
$('.myInputField').keyup(function(){
clearTimeout(typingTimer);
if ($('.myInputField').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
var vale = $('.myInputField').val();
var regexTest = /^\d+(?:\.\d\d?)?$/;
var ok = regexTest.test(vale);
if(!ok){
$('.myInputField').val('');
}
}
http://jsfiddle.net/jWbsE/
You need to change the regular expression used to test the values against.
/^\D+(\.\D\D?)?$/
This will allow numbers with no decimal point, or with a decimal point and one or two digits after.
var dot = fVal.split(".");
var len0 = 0;
var len1 = 0;
if (dot.length == 2) {
len0 = dot[0].length;
len1 = dot[1].length;
} else if (dot.length > 2)
len1 = 3;
else
len1 = 0;
var fValFlt = parseFloat(fVal);
var fValN = isNaN(fVal);
if ((len1 > 2) || fValN == true || fValFlt < 0) {
//failure arguments
} else {
//success arguments
}
In above code fVal is the field value for which you might be checking for.

Searching through international characters with Chosen.js

Has anyone found a fix for searching through international characters using chosen.js?
for example if I have a multi-select field with the following options:
- A French Château
- An English Chateau
And I search for "Cha"
Only the english will show up.
I don't know, if it is not too late for answering, but it could help someone else probably.
The point is to strip diacritics from entered string and from matched option string during comparison.
My modification is working with jquery Chosen plugin in version 1.1.0, downloaded from github.
First you have to have a function to strip diacritics (i've added it after winnow_results())
// strip czech diacritics from string
AbstractChosen.prototype.strip_diacritics= function(string) {
var
translationTable= [
// input with diacritics - add your characters if necessary
"éěÉĚřŘťŤžŽúÚůŮüÜíÍóÓáÁšŠďĎýÝčČňŇäÄĺĹľĽŕŔöÖ",
// stripped output
"eeEErRtTzZuUuUuUiIoOaAsSdDyYcCnNaAlLlLrRoO",
],
output= '';
// scan through whole string
for (var i= 0; i < string.length; i++) {
var charPosition= translationTable[0].indexOf(string[i]);
output+= charPosition == -1 ? string[i] : translationTable[1][charPosition];
}
return output;
}
Then use it in appropriate places in winnow_results() function.
Referencing chosen.jquery.js lines:
line #315
searchText = this.get_search_text();
// replace with
searchText = this.strip_diacritics(this.get_search_text());
line #339
option.search_match = this.search_string_match(option.search_text, regex);
// replace with
option.search_match = this.search_string_match(this.strip_diacritics(option.search_text), regex);
and finally line #345
startpos = option.search_text.search(zregex);
// replace with
startpos = this.strip_diacritics(option.search_text).search(zregex);
And you're done :-).
(I feel like writing some "savegame byte replacement" instruction for extra lives in old DOS game)
Whole modified file at pastebin.
Sept 29th, 2016: Modifications made in Chosen 1.6.2, tested ok.
It doesn't look as though Chosen does this by default - there's no functionality in the code for this.
The source code is here. I've posted the search function below, which is responsible for checking the characters. There's nothing in this function that deals with close characters like that, so you'd either have to write it or request that feature from the Chosen team. This is because, at the core, accented characters and non-accented characters don't have the same ASCII (or Unicode) values. You'd have to have some type of lookup table, and parse that for each character to return "fuzzy" results.
Sorry I couldn't be of more help. I'm sure if you could find a way to modify this function, you could get this working. Again, you'd need lookup tables or something for the underlying code values. Best of luck.
Edit: You may not need lookup tables - perhaps the Regex functionality has a built-in way to do this. Alternatively, you may be able to simply match on anything close to the letter you're searching for.
Chosen.prototype.winnow_results = function() {
var found, option, part, parts, regex, regexAnchor, result, result_id, results, searchText, startpos, text, zregex, _i, _j, _len, _len1, _ref;
this.no_results_clear();
results = 0;
searchText = this.search_field.val() === this.default_text ? "" : $('<div/>').text($.trim(this.search_field.val())).html();
regexAnchor = this.search_contains ? "" : "^";
regex = new RegExp(regexAnchor + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (!option.disabled && !option.empty) {
if (option.group) {
$('#' + option.dom_id).css('display', 'none');
} else if (!(this.is_multiple && option.selected)) {
found = false;
result_id = option.dom_id;
result = $("#" + result_id);
if (regex.test(option.html)) {
found = true;
results += 1;
} else if (this.enable_split_word_search && (option.html.indexOf(" ") >= 0 || option.html.indexOf("[") === 0)) {
parts = option.html.replace(/\[|\]/g, "").split(" ");
if (parts.length) {
for (_j = 0, _len1 = parts.length; _j < _len1; _j++) {
part = parts[_j];
if (regex.test(part)) {
found = true;
results += 1;
}
}
}
}
if (found) {
if (searchText.length) {
startpos = option.html.search(zregex);
text = option.html.substr(0, startpos + searchText.length) + '</em>' + option.html.substr(startpos + searchText.length);
text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
} else {
text = option.html;
}
result.html(text);
this.result_activate(result);
if (option.group_array_index != null) {
$("#" + this.results_data[option.group_array_index].dom_id).css('display', 'list-item');
}
} else {
if (this.result_highlight && result_id === this.result_highlight.attr('id')) {
this.result_clear_highlight();
}
this.result_deactivate(result);
}
}
}
}
if (results < 1 && searchText.length) {
return this.no_results(searchText);
} else {
return this.winnow_results_set_highlight();
}
};

Javascript in list

What's the easiest way to check to see if a number is in a comma delimited list?
console.log(provider[cardType]);
//returns: Object { name="visa", validLength="16,13", prefixRegExp=}
if (ccLength == 0 || (cardType > 0 && ccLength < provider[cardType].validLength)) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}
Seems similar to this SO question.
Just .split() the CSV and use inArray.
Not sure how your sample code relates to checking to see if a number is in a comma delimited list...
Also not sure if this is the easiest way, but it's what springs to mind:
<script type="text/javascript">
var myNumbers = "1,2,3,4,5";
var myArray = myNumbers.split( ',' );
// looking for "4"
for ( var i=0; i<myArray.length; i++ ) {
if (myArray[i] == 4) {
alert('Found it!');
break;
}
}
I do not see where you have a significant comma delimited list in the script you posted.
The fastest way could be something like
var csvList ="a,b,c,d,e,f,g,h";
var testList = ","+csvList+",";
var needle = "f";
alert(testList.indexOf(","+needle+",")!=-1)
just to be different ;)
If it's just a list of comma separated numbers with nothing fancy, you can just use the split method:
var numbers = list.split(",");
This will give you an array of all of the numbers in the list. Checking whether a number is in an array is trivial.
Native JavaScript and therefore cross-browser compliant. Some frameworks provide functions that do this for you, but you don't get more basic than the following.
var numbers = list.split(",");
var count = numbers.length;
var exists = false;
for (var i = 0; i < count; ++i) {
if (numbers[i] == anumber) {
exists = true;
break;
}
}
From your sample, I assume your question was "How do I see if a number is within a range of two values specified by a single-comma-delimited string?":
function inRange( number, stringRange ){
var minmax = stringRange.split(',');
minmax[0] = minmax[0]*1; //convert to number
minmax[1] = minmax[1]*1; //convert to number
minmax.sort(); // Ensure [0] is the min
return number>=minmax[0] && number<=minmax[1];
}
Try this one...
console.log(provider[cardType]); //returns: Object { name="visa", validLength="16,13", prefixRegExp=}
var regExp = new RegExp(",?" + ccLength + ",?");
if (ccLength == 0 || (cardType > 0 && !regExp.test(provider[cardType].validLength)))
{
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
}
else
{
if ($('.credit-card input[name="cc_cvv"]').val().length < 3)
{
triggerNotification('x', 'You must provide a CCV');
return false;
}
}

Javascript word-count for any given DOM element

I'm wondering if there's a way to count the words inside a div for example. Say we have a div like so:
<div id="content">
hello how are you?
</div>
Then have the JS function return an integer of 4.
Is this possible? I have done this with form elements but can't seem to do it for non-form ones.
Any ideas?
g
If you know that the DIV is only going to have text in it, you can KISS:
var count = document.getElementById('content').innerHTML.split(' ').length;
If the div can have HTML tags in it, you're going to have to traverse its children looking for text nodes:
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
This is the same logic that the jQuery library uses to achieve the effect of its text() function. jQuery is a pretty awesome library that in this case is not necessary. However, if you find yourself doing a lot of DOM manipulation or AJAX then you might want to check it out.
EDIT:
As noted by Gumbo in the comments, the way we are splitting the strings above would count two consecutive spaces as a word. If you expect that sort of thing (and even if you don't) it's probably best to avoid it by splitting on a regular expression instead of on a simple space character. Keeping that in mind, instead of doing the above split, you should do something like this:
var count = words.split(/\s+/).length;
The only difference being on what we're passing to the split function.
Paolo Bergantino's second solution is incorrect for empty strings or strings that begin or end with whitespaces. Here's the fix:
var count = !s ? 0 : (s.split(/^\s+$/).length === 2 ? 0 : 2 +
s.split(/\s+/).length - s.split(/^\s+/).length - s.split(/\s+$/).length);
Explanation: If the string is empty, there are zero words; If the string has only whitespaces, there are zero words; Else, count the number of whitespace groups without the ones from the beginning and the end of the string.
string_var.match(/[^\s]+/g).length
seems like it's a better method than
string_var.split(/\s+/).length
At least it won't count "word " as 2 words -- ['word'] rather than ['word', '']. And it doesn't really require any funny add-on logic.
Or just use Countable.js to do the hard job ;)
document.deepText= function(hoo){
var A= [];
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
A[A.length]= hoo.data;
}
else A= A.concat(arguments.callee(hoo));
hoo= hoo.nextSibling;
}
}
return A;
}
I'd be fairly strict about what a word is-
function countwords(hoo){
var text= document.deepText(hoo).join(' ');
return text.match(/[A-Za-z\'\-]+/g).length;
}
alert(countwords(document.body))
Or you can do this:
function CountWords (this_field, show_word_count, show_char_count) {
if (show_word_count == null) {
show_word_count = true;
}
if (show_char_count == null) {
show_char_count = false;
}
var char_count = this_field.value.length;
var fullStr = this_field.value + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;
if (fullStr.length <2) {
word_count = 0;
}
if (word_count == 1) {
wordOrWords = " word";
} else {
wordOrWords = " words";
}
if (char_count == 1) {
charOrChars = " character";
} else {
charOrChars = " characters";
}
if (show_word_count & show_char_count) {
alert ("Word Count:\n" + " " + word_count + wordOrWords + "\n" + " " + char_count + charOrChars);
} else {
if (show_word_count) {
alert ("Word Count: " + word_count + wordOrWords);
} else {
if (show_char_count) {
alert ("Character Count: " + char_count + charOrChars);
}
}
}
return word_count;
}
The get_text function in Paolo Bergantino's answer didn't work properly for me when two child nodes have no space between them. eg <h1>heading</h1><p>paragraph</p> would be returned as headingparagraph (notice lack of space between the words). So prepending a space to the nodeValue fixes this. But it introduces a space at the front of the text but I found a word count function that trims it off (plus it uses several regexps to ensure it counts words only). Word count and edited get_text functions below:
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? ' '+node.nodeValue : get_text(node);
}
}
return ret;
}
function wordCount(fullStr) {
if (fullStr.length == 0) {
return 0;
} else {
fullStr = fullStr.replace(/\r+/g, " ");
fullStr = fullStr.replace(/\n+/g, " ");
fullStr = fullStr.replace(/[^A-Za-z0-9 ]+/gi, "");
fullStr = fullStr.replace(/^\s+/, "");
fullStr = fullStr.replace(/\s+$/, "");
fullStr = fullStr.replace(/\s+/gi, " ");
var splitString = fullStr.split(" ");
return splitString.length;
}
}
EDIT
kennebec's word counter is really good. But the one I've found includes a number as a word which is what I needed. Still, that's easy to add to kennebec's. But kennebec's text retrieval function will have the same problem.
This should account for preceding & trailing whitespaces
const wordCount = document.querySelector('#content').innerText.trim().split(/\s+/).length;
string_var.match(/[^\s]+/g).length - 1;

Categories