Solved

JavaScript Newbie: Removing Comma's

Posted on 2004-04-22
9
528 Views
Last Modified: 2008-03-17
Greetings

Yet another newbie question...with a twist ;->

Hm...it appears comma's break my math-based javascript routines.
Hm...it appears that the inclusion of commas turns my "numbers" into "strings"
Hm..I gotta get rid of these comma's

Well lets see...that means I've got to:

1. check all characters in the string
2. see if the "," (comma) character is in the string
3. if so, remove the comma character

The Code:
=======
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script type="text/javascript">
<!--
// cloak from downlevel browsers

function getLoanAmount(){
var price             = document.frm_search.txt_sales_price.value
var loan            = document.frm_search.txt_loan_amount.value
var ltv             = loan/price;
var calc_ltv      = Math.round((ltv - 0) * 100) + '%';

document.frm_search.txt_ltv.value = calc_ltv

}

// end cloak -->
</script>
</head>

<body>
<form name="frm_search">
<p>
Sales Price/Value (enter dollar amount)<br>
<input type="text" name="txt_sales_price" size="20">
<br>
Loan Amount (enter dollar amount)<br>
<input type="text" name="txt_loan_amount" size="20" onchange="getLoanAmount(this)">
<br>
Loan To Value (LTV)<br>
<input type="text" name="txt_ltv" size="20">
</form>                  

</body>

</html>

</body>

This issue has "illuminated" the need to learn how to manipulate string functions. My google search for a simple explanation of how to do this turned up (at best) the following (below) which ihave gleaned to be regular expressions (of which I know very little about).

var objRegExp = /,/g; //search for commas globally
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

So it appears im due for a crash course in string manipulation. Since I learn best when confronting a problem I seek an "understanding of the approach" to solving the issues presented in items (1,2 & 3) above. [Please read my newbie disclaimer before you answer (as it will affect the dispensation of points)]

==========================
QUESTION/ANSWER DISCLAIMER
==========================

About Answers

Please note: I am a rookie, the "greenest" of greenhorns. When I submit a question what I am looking for is a clear understanding of WHAT I AM DOING WRONG (the theory). Many have supplied code samples with no explanation. I have found that this only helps SOMETIMES. If I don't understand the error - I (in my "green"-ness) - will most likely commit the same error over and over again UNTIL I UNDERSTAND why I keep committing the same error.

That being said... CODE ONLY ANSWERS WILL GET NO POINTS FROM ME! Not to be nasty, but again I'm trying to learn. So please, simply ADD A SENTENCE OR TWO EXPLAINING WHAT I'M DOING WRONG to help clear the fog.

About Points

I don't belive in giving ANYTHING less than 500 points because I consider EVERY question "extremely important". Important to either a project (yeah right) or my continued journey out of the land of the Newbie. On the other hand You Guys and Gals already know this stuff and make money doing it, yet you still find the time to answer questions to the benefit of us all. Thats definitely worth 500 point to me.

Thank you for your patience and understanding

the_sleeper
0
Comment
Question by:the_sleeper
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 25

Expert Comment

by:James Rodgers
ID: 10889479
try cahnging your function to this

function getLoanAmount(){
var price           = eval(document.frm_search.txt_sales_price.value.replace(',',''))
var loan          = eval(document.frm_search.txt_loan_amount.value.replace(',',''))
var ltv           = loan/price;
var calc_ltv     = Math.round((ltv - 0) * 100) + '%';

document.frm_search.txt_ltv.value = calc_ltv

}
0
 
LVL 63

Accepted Solution

by:
Zvonko earned 250 total points
ID: 10889565
Here my proposal:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script type="text/javascript">
<!--
// cloak from downlevel browsers

function getLoanAmount(theField){
  theForm = theField.form;
  var price = theForm.txt_sales_price.value = theForm.txt_sales_price.value.replace(/[^.\d]/g,"")*1;
  var loan = theForm.txt_loan_amount.value = theForm.txt_loan_amount.value.replace(/[^.\d]/g,"")*1;
  var ltv = loan/price;
  var calc_ltv  = Math.round((ltv) * 100) + '%';
  theForm.txt_ltv.value = calc_ltv

}

// end cloak -->
</script>
</head>
<body>
<form name="frm_search">
<p>
Sales Price/Value (enter dollar amount)<br>
<input type="text" name="txt_sales_price" size="20">
<br>
Loan Amount (enter dollar amount)<br>
<input type="text" name="txt_loan_amount" size="20" onchange="getLoanAmount(this)">
<br>
Loan To Value (LTV)<br>
<input type="text" name="txt_ltv" size="20">
</form>              
</body>
</html>


And you have to ask answers and not expect explanations. How could I know what you need and what you already learned?

Ok, here some short explanations.
Use form name independed functions. When you already passed one <input> field by this reference, then use its form reference to get form object.
RegExp to replace anything but digits and dots is this: String.replace(/[^.\d]/g,"")
The multiply by one is only to convert empty strings to zero value.

Please ask if you have more questions.

0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 10889569
this is better removes all commas, but  does not validate if the value is a number

function removeSep(strSrc,strFind,strRep){
      while (strSrc.indexOf(strFind) !=-1){
            strSrc=strSrc.replace(strFind,strRep);
      }
      return strSrc
}

function getLoanAmount(){
var price = removeSep(document.frm_search.txt_sales_price.value,',','')
var loan = removeSep(document.frm_search.txt_loan_amount.value,',','')
var ltv           = loan/price;
var calc_ltv     = Math.round((ltv - 0) * 100) + '%';

document.frm_search.txt_ltv.value = calc_ltv

}
0
 
LVL 25

Assisted Solution

by:James Rodgers
James Rodgers earned 200 total points
ID: 10889710
Zvonko's use of teh regualr expression is a better solution but heres the explanation for my code

your function slightly modified
take the field values and pass them to a function called removeSep
the function has three arguments, all strings, sopurce string, string to look for, replacement value for string to look for
function getLoanAmount(){
var price = removeSep(document.frm_search.txt_sales_price.value,',','')
var loan = removeSep(document.frm_search.txt_loan_amount.value,',','')
var ltv           = loan/price;
var calc_ltv     = Math.round((ltv - 0) * 100) + '%';

document.frm_search.txt_ltv.value = calc_ltv

}

the function takes three arguments
strSrc - the source string in which you want to replace characters
strFind - the characters you want to replace, note this is an absolute if strFind is ab it will find 'ab' not a or b
strRep - the string with which to replace strFind

function removeSep(strSrc,strFind,strRep){
     while (strSrc.indexOf(strFind) !=-1){ //if the location of the string strFind is -1 (not found) then exit the loop
          strSrc=strSrc.replace(strFind,strRep); // replace the instance of strFind in strSrc with strRep
     }
     return strSrc; //return the resulting value of the loop, if there is no instance of strFind in strSrc, strSrc is returned
}



0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 31

Assisted Solution

by:GwynforWeb
GwynforWeb earned 50 total points
ID: 10889782
This is really simple and works

var price           = document.frm_search.txt_sales_price.value.replace(/,/g,'')

replaces the commas in document.frm_search.txt_sales_price.value with nothing and assigns the value to price. /,/ refers to commas and the g means globally ie all of them. (So use /,/g )


The script becomes

<script type="text/javascript">
<!--
// cloak from downlevel browsers

function getLoanAmount(){
var price           = document.frm_search.txt_sales_price.value.replace(/,/g,'')
var loan          = document.frm_search.txt_loan_amount.value.replace(/,/g,'')
var ltv           = loan/price;
var calc_ltv     = Math.round((ltv) * 100) + '%';

document.frm_search.txt_ltv.value = calc_ltv

}

// end cloak -->
</script>
</head>

<body>
<form name="frm_search">
<p>
Sales Price/Value (enter dollar amount)<br>
<input type="text" name="txt_sales_price" size="20">
<br>
Loan Amount (enter dollar amount)<br>
<input type="text" name="txt_loan_amount" size="20" onchange="getLoanAmount(this)">
<br>
Loan To Value (LTV)<br>
<input type="text" name="txt_ltv" size="20">
</form>              

</body>
0
 

Author Comment

by:the_sleeper
ID: 10890420
OK here is what i have digested...(points coming)

@Zvonko: I stared at your code and comments until it made sense to me. Good point on form name independant functions. will do.
@Jester_48: By reading through your code and your explanations I now have a grasp on the mechanics of search end replace functions, and agree with you that  Zvonko offers the best possible approach (however, I will feel much better about "why" when i learn regular expressions). The you cleared the fog. Kudo's.

@GwynforWeb: also, a nice approach. Thanks for the explantion of the regexp characters...

Overall, Zvonko does offer the best approach at solving the problem not to mention the clarification of function naming conventions (givin my limited range of clarity so excuse me if i'm wrong ;->).

But all comments all deeply appreciated.  Thank You  




0
 

Author Comment

by:the_sleeper
ID: 10890466
uh...anyone recommend a good online javascript tutorial? my book (Beginning Javascript 2nd edtition) will not ship until the 26th.

thanks
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10890528
The problem with RegExp is that explanation become more complicated then the expressions itself.
So best approach is to try to use the simples one like the upper replace single character example.

For online references they are to many different.
Check this for the start:
http://www.w3schools.com/js/default.asp

Thanks for the points.

Cheers,
Zvonko

0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 10890550
glad i could help

thanks for the points
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now