hey guys should be a easy one...I have some javascript that is turning my input values into currency values. Problem is it will fail if I try to type in .5 heres is my code:
function handleCurrency(formName,fieldName)
{
var enteredValue = document.forms[formName].elements[fieldName].value;
if ( enteredValue.isCurrency() )
{
alert("This is currency " + enteredValue )
// Put the nicely formatted back into the text box.
document.forms[formName].elements[fieldName].value = enteredValue.toCurrency();
}
}
jsp:
<td><input type="text" name="replacementCost" onchange="handleCurrency('NsnAdd','replacementCost')" value="<ctl:currencyFormat currency='${form.replacementCost}'/>" onkeypress="javascript:return noenter();" <c:if test="${!lock.locked}">disabled="disabled"</c:if> /></td>
How can I make it so that .5 is allowable also to be formatted?
custom javascript:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
function stringIsCurrency()
{
if (patternWithoutCommas.test(this))
{
return true;
}
else if (patternWithCommas.test(this))
{
return true;
}
return false;
}
function stringToCurrency()
{
if (this == '') return this;
var str = this.replace(/[$,]+/g,'');
sign = (str == (str = Math.abs(str)));
str = Math.floor(str*100+0.50000000001);
cents = str%100;
str = Math.floor(str/100).toString();
if (cents<10) cents = "0" + cents;
for (var i = 0; i < Math.floor((str.length-(1+i))/3); i++)
{
str = str.substring(0,str.length-(4*i+3))+','+
str.substring(str.length-(4*i+3));
}
str = '$' + ((sign)?'':'-') + str + '.' + cents;
return str;
}
String.prototype.isCurrency = stringIsCurrency;
String.prototype.toCurrency = stringToCurrency;
basically it needs to allow .5 and not just 0.5
this needs to be updated:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
You have not shown your code for isCurrency.
Here's how I would do it:
function isCurrency( val )
{
return /^\$?(?:\d[\d,]*)?(?:.\d\d?)?$/.test( val );
}
See it here in action: http://regexr.com?3103a
Now that you have provided your code, here's my proposed solution.
While there are many things I would have done differently,
in order to keep the spirit of your code, just change this:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
to this:
var patternWithCommas = /^\s*\$?-?((\d{1,3}){1}(,\d{3})?)?(\.\d{1,2})?\s*$/;
var patternWithoutCommas = /^\s*\$?-?(\d+)?(\.\d{1,2})?\s*$/;
which would make the dollar amount optional.
Related
I am a beginner at js and have a project due by the end of day. I have to display an array with temps added and have set up an object to hold this array. My problem is that the message won't display and the for statement doesn't increment. When passed through both the var i and count come back undefined. I know there is a lot missing from this code but at this point I have tried to stream line it so that I can debug this issue. The date I will deal with later.
Here is my code:
var temps = [];
function process() {
'use strict';
var lowTemp = document.getElementById('lowTemp').value;
var highTemp = document.getElementById('highTemp').value;
var output = document.getElementById('output');
var inputDate = (new Date()).getTime();
var temp = {
inputDate : inputDate,
lowTemp : lowTemp,
highTemp : highTemp
};
var message = '';
if (lowTemp == null) {
alert ('Please enter a Low Temperature!');
window.location.href = "temps.html";
} else if (highTemp == null) {
alert ('Please enter a High Temperature!');
window.location.href = "temps.html";
} else {
lowTemp = parseFloat(lowTemp, 10);
highTemp = parseFloat(highTemp, 10);
}
if (temp.value) {
temps.push(temp.inputDate, temp.lowTemp, temp.highTemp)
var message = '<h2>Temperature</h2><ol>';
for (var i = 0, count = temps.length; i < count; i++) {
message += '<li>' + temps[i] + '</li>'
}
message += '</ol>';
output.innnerHTML = message;
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
}
window.onload = init;
Here is my new code:
var temps = [];
function process() {
'use strict';
var lowTemp = document.getElementById('lowTemp').value;
var highTemp = document.getElementById('highTemp').value;
var output = document.getElementById('output');
var inputDate = (new Date()).getTime();
var temp = {
inputDate : inputDate,
lowTemp : lowTemp,
highTemp : highTemp
};
var message = '';
if (lowTemp == null) {
alert ('Please enter a Low Temperature!');
window.location.href = "temps.html";
} else if (highTemp == null) {
alert ('Please enter a High Temperature!');
window.location.href = "temps.html";
} else {
lowTemp = parseFloat(lowTemp, 10);
highTemp = parseFloat(highTemp, 10);
}
if (temp.value) {
temps.push(temp.inputDate, temp.lowTemp, temp.highTemp)
var message = '<h2>Temperature</h2><ol>';
for (var i = 0, count = temps.length; i < count; i++) {
message += '<li>' + temps[i] + '</li>'
}
message += '</ol>';
output.innnerHTML = message;
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
}
window.onload = init;
There are some big issues with your code:
You should never compare anything to NaN directly. The correct comparison should be:
if (isNaN(lowTemp)) {
You're using curly braces when not needed. You should remove both curly braces:
{window.location.href = "temps.html";}
The function parseFloat expects only one parameter: the string to be converted. You're probably confusing it to parseInt which expects both the string and the radix of the conversion.
You're using the temp's property value, but you have never setted it, so, the condition where you check if it exists will always return false, and the push method that you want to debug will never be called, since it's inside that if statement.
Finally, you're closing a li tag at the end, but you have never opened it. You should probably be closing the ol tag you have opened in the begining.
The rest of your code seems pretty OK for me.
Talking about debugging, you should read the Google Chrome's Debugging Javascript Tutorial.
I am trying to make a function in javascript that would expand/split a string with dashes and show the process ( line by line ) using recursion.
for example, the string "anna" would become:
expand("anna") = expand("an")+"---"+expand("na") ->
"a"+"---"+"n"+"---"+"n"+"---"+"a"
and the desired output would be:
anna
an---na
a---n---n---a
I have achieved doing the following so far (I know it might not be the solution I am looking):
expand("anna") = an+"---"+expand("na")
= an+"---"+n+"---"+expand("a");
= an+"---"+n+"---+"a"
the output I am getting is:
an---n---a
I can't seem to concatenate the head though to do the first example.
My javascript function of expand is as follows:
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return word.substr(0,mid) + " " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I would need some tips to do this, otherwise (if it's the wrong stackexchange forum), please guide me where to post it.
this is my crazy attempt
var Word = function(str) {
this.isSplitable = function() {
return str.length > 1;
}
this.split = function() {
var p = Math.floor(str.length / 2);
return [
new Word(str.substr(0,p)),
new Word(str.substr(p,p+1))
];
}
this.toString = function() {
return str;
}
}
var expand = function(words) {
var nwords = [];
var do_recur = false;
words.forEach(function(word){
if(word.isSplitable()) {
var splitted = word.split();
nwords.push(splitted[0]);
nwords.push(splitted[1]);
do_recur = true;
}else{
nwords.push(word);
}
});
var result = [];
nwords.forEach(function(word){
result.push( word.toString() );
});
var result = result.join("--") + "<br/>";
if(do_recur) {
return result + expand(nwords);
}else{
return "";
}
}
document.write( expand([new Word("anna")]) );
This is what you need
expand = function(word) {
return [].map.call(word, function(x) {return x+'---'}).join('')
};
The joy of functional programming.
And with added code to deal with last character:
function expand(word) {
return [].map.call(word, function(x, idx) {
if (idx < word.length - 1)
return x+'---';
else return x
}).join('')
}
As I said that it is impossible to display the "process" steps of recursion while using recursion, here is a workaround that will output your desired steps:
var levels = [];
function expand(word, level) {
if (typeof level === 'undefined') {
level = 0;
}
if (!levels[level]) {
levels[level] = [];
}
levels[level].push(word);
if (word.length <= 1) {
return word;
} else {
var mid = Math.ceil(word.length/2);
return expand(word.substr(0, mid), level+1) + '---' + expand(word.substr(mid), level+1);
}
}
expand('anna');
for (var i = 0; i < levels.length; i++) {
console.log(levels[i].join('---'));
}
to see all steps the best that I whold do is:
function expand(word) {
if (word.length<=1) {
return word;
} else {
var mid = word.length/2;
var str1 = word.substr(0,mid);
var str2 = word.substr(mid,word.length);
document.write(str1 + "---" + str2 + "<br></br>");
return expand(str1) + "---" + expand(str2);
}
}
document.write(expand("anna"));
You have to return the two parts of the string:
function expand(word) {
output="";
if (word.length<=1) {
output+=word;
return output;
} else
{
var mid = word.length/2;
output+=word.substr(0,mid)+"---"+word.substr(mid)+" \n";//this line will show the steps.
output+=expand(word.substr(0,mid))+"---"+expand(word.substr(mid,word.length-1))+" \n";
return output;
}
}
console.log(expand("anna"));
Edit:
I added the output var and in every loop I concatenate the new output to it.
It should do the trick.
Hope the problem is in your first part. According to your algorithm, you are splitting your string anna in to two parts,
an & na
so you need to expand both parts until the part length is less than or equal to one. so your required function is the below one.
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return expand(word.substr(0,mid)) + " --- " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I meet a trouble with a function. actually I need to make this function to perform a calculation on some text fields. When I worked on a single line no problems. But recently, someone asked to make a table with multiple lines (one line can be added dynamically) so, I do the following function so that it can not only duplicate line but id change all the fields concerned, so I add class to these fields. therefore I proceed as follows:
function clone(line) {
newLine = line.cloneNode(true);
line.parentNode.appendChild(newLine);
var tab = document.getElementsByClassName('libelle_debours')
var i = -1;
while (tab[++i]) {
tab[i].setAttribute("id", "_" + i);
};
var cab = document.getElementsByClassName('ht_no_tva')
var j = -1;
while (cab[++j]) {
cab[j].setAttribute("id", "_" + j);
};
var dab = document.getElementsByClassName('ht_tva')
var k = -1;
while (dab[++k]) {
dab[k].setAttribute("id", "_" + k);
};
var eab = document.getElementsByClassName('taux')
var l = -1;
while (eab[++l]) {
eab[l].setAttribute("id", "_" + l);
};
var fab = document.getElementsByClassName('tva')
var m = -1;
while (fab[++m]) {
fab[m].setAttribute("id", "_" + m);
};
}
function delRow() {
var current = window.event.srcElement;
//here we will delete the line
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
The problem in fact is the second function that is used to make the calculation:
function calcdebours() {
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva = Math.round((((ht_tva) * (taux)) / 100) * 100) / 100;;
if (taux == '') {
taux = 0;
}
if (ht_no_tva == '') {
ht_no_tva = 0;
}
if (ht_tva == '') {
ht_tva = 0;
}
document.getElementById('debours_montant_tva').value = tva;
document.getElementById('debours_montant_ttc').value = (tva) + parseFloat(ht_tva) + parseFloat(ht_no_tva)
}
function
montant_debours() {
var ttc = document.getElementById('debours_montant_ttc').value;
var ttc2 = document.getElementById('debours_montant_ttc2').value;
if (ttc == '') {
var ttc = 0;
} else {
var ttc = document.getElementById('debours_montant_ttc').value;
}
if (ttc2 == '') {
var ttc2 = 0;
} else {
var ttc2 = document.getElementById('debours_montant_ttc2').value;
}
tx = parseFloat(ttc) + parseFloat(ttc2);
document.getElementById('ttc_cheque').value = Math.round(tx * 100) / 100;
}
As Id are not the same, do I have to create as many functions
there are lines?
Is it possible to fit a single function to process each line?
If so can you tell me how?
If I'm not mistaken you can use for loop and append increment to the end of element's id. Like this:
trs = document.getElementById('container Id').getElementsByTagName('tr');
For (var i = 1, i <= trs.length; i++)
{
var el = document.getElementById('debours_montant_ttc' + i);
}
I have a string like "word_count". How can I transform it to "WordCount" in an elegant way using JavaScript? My decision seems too complicated to me. I'll be very grateful for your help.
function titleCase(str)
{
return str.split("_")
.map(function (s) { return s.charAt(0).toUpperCase() + s.slice(1); })
.join("");
}
Take a look at this. I don't want to just copy paste everything here, but it seems to be just what you're looking for.
Here is the function modified to fit your request:
String.prototype.toCamel = function(){
return this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');});
};
And here it is in action.
You can use a regular expression to match either a letter at the start of the string or a letter after an underscore, and use a callback to turn the letter into uppercase:
s = s.replace(/(?:^|_)([a-z])/g, function(m, g){
return g.toUpperCase();
});
Demo: http://jsfiddle.net/Guffa/ByU6P/
Simple, like this:
var string = "word_count".split("_");
for(var i = 0; i<string.length;i++) {
string[i] = string[i].charAt(0).toUpperCase() + string[i].substr(1);
}
var myNiceString = string.join();
If you want to add it to the String object, you can do this:
String.prototype.titleCase = function() {
var split = this.split("_");
for(var i = 0; i<split.length;i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].substr(1);
}
return split.join("");
}
You'd call it like "word_count".titleCase();
You can use a function like the following:
var Pascalize = function(word) {
var x = word;
result = '';
if(-1 != word.indexOf('_')) {
x = word.split('_');
for(var i=0;i<x.length;i++) {
result += x[i].substr(0, 1).toUpperCase() + x[i].substr(1);
}
}
if('' == result) { result = word; }
return result;
};
var PascalCaseString = Pascalize("this_is_a_test");
// PascalCaseString value is now 'ThisIsATest'
Here's a working example
var str = "word_count";
var re = /\b(.)([^_]+)_(.)/;
var newWord = str.replace(re, function(m,f,t,l){ return f.toUpperCase() + t + l.toUpperCase();})
console.log(newWord);
Using jQuery, you could do the following:
var result = '';
$.each('word_count'.split('_'), function(idx,elem){
result = result + elem.substr(0,1).toUpperCase() + elem.substr(1);
});
New version (works with any amount of _):
function fixString(sString) {
var aWords = sString.split("_"),
sResults = "";
for (var i in aWords)
sResults += aWords[i].charAt(0).toUpperCase() + aWords[i].slice(1);
return sResults;
}
The compressed form:
function fixString(c){var d=c.split("_"),a="";for(var b in d){a+=d[b].charAt(0).toUpperCase()+d[b].slice(1)}return a};
Old:
function fixString(sString) {
return sString.replace(/(.*)_(.*)/, function(sWhole, $1, $2, sWTF) {
return ucfirst($1) + ucfirst($2);
} )
function ucfirst (str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}
... or the compressed version:
function fixString(b){return b.replace(/(.*)_(.*)/,function(e,c,f,d){return a(c)+a(f)});function a(d){d+="";var c=d.charAt(0).toUpperCase();return c+d.substr(1)}};
Of course, this is used like fixString("word_count") which results in your desired WordCount.
I've looked at all the answer and none did precisely what I wanted. I wanted an idempotent function which converted to camelCase (not PascalCase) and I liked the String prototype extension approach (although obviously this isn't always the best medicine).
Anyway, here's where I ended up:
String.prototype.camelize = function(){
var pascalCase = this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');
});
return pascalCase.charAt(0).toLowerCase() + this.slice(1);
};
var aStringLike = "word_count";
// magic follows
aStringLike = "WordCount";
I'm trying to write "fuzzy" match and I can't find a way to solve this problem:
Data in: makrusakkk, query: mrk, expected result: <b>m</b>ak<b>r</b>usa<b>k</b>kk.
RegExp: "makrusakkk".match(/(m).*?(r).*?(k)/i) returns ["makrusak", "m", "r", "k"].
So the question is: is there a way to get the expected result using RegExp?
I think using regular expression for such problem makes things just more complicated. The following string and loop based solution would lead to the result:
function fuzzySearch(query, input) {
var inds = patternMatches(query, input);
if(!inds) return input;
var result = input;
for(var i = inds.length - 1; i >= 0; i--) {
var index = inds[i];
result = result.substr(0,index) +
"<b>" + result[index] + "</b>" +
result.substr(index+1);
}
return result;
}
function patternMatches(query, input) {
if(query.length <= 0) {
return [];
} else if(query.length == 1) {
if(input[0] == query[0]) return [0];
else return [];
} else {
if(input[0] != query[0])
return false;
var inds = [0];
for(var i = 1; i < query.length; i++) {
var foundInd = input.indexOf(query[i], inds[i-1]);
if(foundInd < 0) {
return [];
} else {
inds.push(foundInd);
}
}
return inds;
}
}
var input = "makrusakkksd";
var query = "mrk";
console.log(fuzzySearch(query, input));
console.log(patternMatches(query, input));
Here's a live demo too: http://jsfiddle.net/sinairv/T2MF4/
Here you will need for:
function search_for_it(txt, arr){
for(i=0;i<arr.length;i++){
var reg = new RegExp(arr[i], "i");
txt = txt.replace(reg, "<b>"+arr[i]+"</b>");
}
return txt;
}
search_for_it("makrusakkk", ["m","r","k"]);
//return "<b>m</b>a<b>k</b><b>r</b>usakkk"
PS: Your expected result is incorrect. There is a k after the first a.
is there a way to get an expected result using RegExp?
There is.
"makrusakkk".replace(/(m)(.*?)(r)(.*?)(k)/i, '<b>$1</b>$2<b>$3</b>$4<b>$5</b>')
I feel vaguely dirty for this, but...regardless; here's one way to do it:
$('#s').keyup(
function(e) {
var w = e.which;
if (w == 8 || w == 46) {
return false;
}
var listElems = $('ul:first li'),
search = $(this).val().replace(/w+/g, ''),
r = search.split(''),
rString = [];
$.each(r, function(i, v) {
rString.push('(' + v + ')');
});
var reg = new RegExp(rString.join('(\\d|\\D)*'), 'gi');
listElems.each(
function() {
if (!$(this).attr('data-origtext')) {
$(this).attr('data-origtext', $(this).text());
}
$(this).html($(this).attr('data-origtext').replace(reg, '<b>$&</b>'));
});
});
JS Fiddle demo.
It could, almost certainly, benefit from quite some simplification though.
References:
attr().
:first selector.
join().
keyup().
push().
RegExp().
replace().
split().
text().
val().