Solved

JavaScript Newbie: Removing Comma's

Posted on 2004-04-22
9
540 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
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
 
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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 …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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…

733 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