JS with dollar signs and commas

Here is some old code that worked a few years ago. It’s is now not working and all I want to do is to, as you tab through the form, place $ signs and commas. Rather than 1000 it would be as you tab out of the field: $1,000.

For the life of me I can’t seem to get anything to work! Any help would be appreciate.

Code:

<SCRIPT LANGUAGE=javascript>
<!--

function isint(box){
	value = box.value
	value = value.replace("$","")
	for(i=0; value.search(",") > 0;){
		value = value.replace(",","")
	}
	for(i = 0; i != value.length; i++){
		aChar = value.substring(i,i+1)
		if((aChar < "0" || aChar > "9")){
			alert('Field needs to be a whole number or dollar amount, leave off decimals or cents.')
			box.value = 0	
			return	
		}		
	}
}

function isdbl(box){
	value = box.value
	value = value.replace("%","")
	value = value.replace("$","")
	for(i=0; value.search(",") > 0;){
		value = value.replace(",","")
	}
	for(i = 0; i != value.length; i++){
		aChar = value.substring(i,i+1)
		if((aChar < "0" || aChar > "9") && (aChar != ".")){
			alert('Field needs to be a number.')
			box.value = 0	
			return	
		}		
	}
	box.value =  value
}

//-->
</SCRIPT>

<%if ie then%>
		<script language=vbscript>
		function dollar(this)
			isdbl(this)
			this.value = formatcurrency(this.value,0)
		end function
		function putcommas(this)
			this.value = formatnumber(this.value,0,0,0,true)
		end function
		</script>
<%else%>
		<script language=javascript>
		function dollar(field){

		}
		function caprate(field){

		}
		</script>
<%end if%>

Here is the form input:

<tr>
      <td width="177" align="right" height="25">Sales Price:&nbsp; </td>
      <td width="146" height="24"><input type="text" name="SalesPrice"  size="20" tabindex="1" onchange='dollar(this);' > </td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="250" height="25">Check all that is appropriate:</td>
      <td width="177" height="25">&nbsp;</td>
    </tr>

I know that I don’t have to most likely be concerned with IE if then statement, but there must be something simple that I am missing.

Thank you for your help.

That IE code only supplies a dollar function when IE is being used. I can’t tell from that code how it’s supposed to work when not using IE.

What do you think of using Number.prototype.toLocaleString() which lets you do the following:

Number(10000).toLocaleString("US", {
  style: "currency",
  currency: "USD"
});

Which gives you: $10,000

I tried scraping all of the other JS code that I mentioned and used:

<script language=javascript>
	    Number(10000).toLocaleString("US", {
	        style: "currency",
	        currency: "USD"
	    });

		</script>

…and then for the form using:


   <tr>
      <td width="177" align="right" height="25">Sales Price:&nbsp; </td>
      <td width="146" height="24"><input type="text" name="SalesPrice"  size="20" tabindex="1" style: "currency" > </td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="250" height="25">Check all that is appropriate:</td>
      <td width="177" height="25">&nbsp;</td>
    </tr>

The above didn’t work. Did I do something wrong in the code?

Thanks, I appreciate it.

Here’s an example where that toLocalString() function is being used to update the form field whenever it’s changed.

function dollar(evt) {
  var field = evt.target;
  field.value = Number(field.value).toLocaleString("US", {
    style: "currency",
    currency: "USD"
  });
}

Paul

Thank you for that. You made that simple and it does work and I appreciate that very much.

One last thing, if I had a % field in the form, how can you add the % to the JS and then to the onchange event?

Again Thanks!!!

Then it wouldn’t be a currency field, and would need to be treated in a different manner.

Please supply the HTML form code that contains the fields that you intend to work with.

This is the form that handles the %: So it would even be easy to add another JS to handle just the percentage.

<td width="177" height="21" align="right">
        <p align="right">Interest rate:&nbsp; </td>
      <td width="148" height="21"><input type="text" name="InterestRate" size="11" tabindex="3" onchange=isdbl(this)>
       </td>

Thank You!

It’s not appropriate to use inline HTML event attributes. Instead, we give the form element a unique identifier, and access the form elements via the elements collection.

<form id="myForm">
    ...
    <input type="text" name="SalesPrice" size="20" tabindex="1">
    ...
</form>
var form = document.querySelector("#myForm");
form.elements.SalesPrice.addEventListener("change", dollar);

One of the reasons why it’s beneficial to do things that way, is that you can then scale the process quite easily.
Place a class of dollar on all of the appropriate fields, and all of them can then be dealt with at the same time.

    <input type="text" name="SalesPrice" class="dollar" size="20" tabindex="1"> 
document.querySelectorAll("form .dollar").forEach(function (field) {
    field.addEventListener("change", dollar);
});

It then doesn’t matter if there’s one, or a hundred of those dollar form fields. They’ll all be properly handled.

The same can be done with the percentage. Give it a class name, then attach an event using the class name.

    <input type="text" name="InterestRate" class="percentage" size="11" tabindex="3">
document.querySelectorAll("form .percentage").forEach(function (field) {
    field.addEventListener("change", percentage);
});

The working code for this example is found at https://jsfiddle.net/pmw57/g0dn7cLb/2/

That is a lot to take in from a novice at JS!! I need to go for now and will be gone for a copy of days but I WILL give this a try and get back to you.

Thank you so much for your time and your expertise. I wish I had your understanding of JS like you do.

Thank you - will be in touch with a reply.

Hi Paul,

I am back and looking at your code:

<SCRIPT LANGUAGE=javascript>
<!--

    function getNumber(str) {
        return Number(str.replace(/[^0-9\.-]+/g, ""));
    }

    function dollar(evt) {
        var field = evt.target;
        field.value = getNumber(field.value).toLocaleString("US", {
            style: "currency",
            currency: "USD"
        });
    }

    function percentage(evt) {
        var field = evt.target;
        field.value = getNumber(field.value) + "%";
    }

    document.querySelectorAll("form .dollar").forEach(function (field) {
        field.addEventListener("change", dollar);
    });
    document.querySelectorAll("form .percentage").forEach(function (field) {
        field.addEventListener("change", percentage);
    });
//-->
</SCRIPT>

I then gave each field a class=“dollar” or class=“percentage”.

It doesn’t seem to work nor does the example that I clicked on that you gave. I do understand your logic so I appreciate that explanation.

Looking forward to your response.

Thank you.

That’s interesting, let’s try and find out why.

I was using only the Chrome web browser for testing. Could the issue be related to a different web browser? The test code at https://jsfiddle.net/pmw57/g0dn7cLb/2/ seems to work in Edge and Firefox as well.

Could it be that what you are expecting is different from how it behaves? The way that it’s designed to behave is that the formatting happens when you leave the form field. It doesn’t happen when you are in the middle of making changes to the form field.

Hopefully that helps somewhat to finding out why it doesn’t seem to work for you.

Well, that’s interesting because I thought the same thing regarding browsers. But I didn’t try your test page. Results are interesting. It works for me in FF and Chrome but not in IE. I am using Windows 8.1. So I tried it on a Windows 10 in both IE and Edge and neither worked on your test page.

When I place your code into my page I can’t get it to work even in Chrome.

Here again is what I have to be sure it’s correct:

<SCRIPT LANGUAGE=javascript>
<!--

    function getNumber(str) {
        return Number(str.replace(/[^0-9\.-]+/g, ""));
    }

    function dollar(evt) {
        var field = evt.target;
        field.value = getNumber(field.value).toLocaleString("US", {
            style: "currency",
            currency: "USD"
        });
    }

    function percentage(evt) {
        var field = evt.target;
        field.value = getNumber(field.value) + "%";
    }

    document.querySelectorAll("form .dollar").forEach(function (field) {
        field.addEventListener("change", dollar);
    });
    document.querySelectorAll("form .percentage").forEach(function (field) {
        field.addEventListener("change", percentage);
    });
//-->
</SCRIPT>
      <td width="177" align="right" height="25">Sales Price:&nbsp; </td>
      <td width="146" height="24"><input type="text" name="SalesPrice"  size="20" tabindex="1"  class="dollar"> </td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="250" height="25">Check all that is appropriate:</td>
      <td width="177" height="25">&nbsp;</td>
    </tr>
 <td width="177" height="21" align="right">
        <p align="right">Interest rate: </td>
      <td width="148" height="21"><input type="text" name="InterestRate" size="11" tabindex="3" class="percentage">
        </td>

It’s the querySelectorAll code that’s causing the problem, specifically, using forEach on them.
We can add that ability to browsers that don’t support it, by putting this at the top of the code:

if (!Nodelist.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

The code now works on Internet Explorer, and should be more widely capable of working elsewhere too.
The updated code is https://jsfiddle.net/g0dn7cLb/3/

The test code in the link doesn’t work in IE for me and I tried it in Chrome and it doesn’t work either. I also cleared my cache thinking that could be an issue; no different results.

Sorry for the trouble, a simple spelling mistake was made were Nodelist needs to be NodeList
The code worked in IE before adding in the if statement that contained that spelling mistake.

It should be fixed in the code at https://jsfiddle.net/pmw57/g0dn7cLb/4/

Nothing to be sorry about! But I am sorry that I might be troubling you because I do appreciate your help and I still can’t get this to work.

I copied and pasted the JS and your 2 input fields and it’s still not working for me in any browser. And for the life of me I don’t know why!

Is this the correct tag to use for: ? I also tried text/javascript and same results. It’s also in the .

Any thoughts?

Thanks.

text/javascript is the right one to use, but the type is not needed for JavaScript and can be removed, leaving you with just <script></script>

That you are putting it in the <head> section is the cause of your problem. When the code runs, the body of the html doesn’t yet exist, so it can find nothing on which to add the event handlers.

Move the script to the end of the body, just before the </body> tag and it should work well for you.

I have the entire page stripped down to just this and still not working. It’s an asp page - wouldn’t think that would make a difference?:

<html>

<head>


</head>


<script>


    if (!NodeList.prototype.forEach) {
        NodeList.prototype.forEach = Array.prototype.forEach;
    }

    function getNumber(str) {
        return Number(str.replace(/[^0-9\.-]+/g, ""));
    }

    function dollar(evt) {
        var field = evt.target;
        field.value = getNumber(field.value).toLocaleString("US", {
            style: "currency",
            currency: "USD"
        });
    }

    function percentage(evt) {
        var field = evt.target;
        field.value = getNumber(field.value) + "%";
    }

    document.querySelectorAll("form .dollar").forEach(function (field) {
        field.addEventListener("change", dollar);
    });
    document.querySelectorAll("form .percentage").forEach(function (field) {
        field.addEventListener("change", percentage);
    });

</script>

<body>





	

<form id="myForm">
  <table>
    <tr>
      <td width="177" align="right" height="25">Sales Price:&nbsp; </td>
      <td width="146" height="24">
        <input type="text" name="SalesPrice" class="dollar" size="20" tabindex="1"> </td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="1" align="right" height="25">&nbsp;</td>
      <td width="250" height="25">Check all that is appropriate:</td>
      <td width="177" height="25">&nbsp;</td>
    </tr>
    <tr>
      <td width="177" height="21" align="right">
        <p align="right">Interest rate:&nbsp; </td>
      <td width="148" height="21">
        <input type="text" name="InterestRate" class="percentage" size="11" tabindex="3">
      </td>
    </tr>
  </table>
</form>




</body>

</html>

[quote=“javascript7, post:18, topic:284674, full:true”]
I have the entire page stripped down to just this and still not working. It’s an asp page - wouldn’t think that would make a [/quote]

That script cannot work where it is. Nothing is allowed to be between the head and the body sections of the page.

Move the script down until it’s at the end of the body, just before the </body> tag which closes the body section of the page.

I’ve just been notified (thanks @Mittineague) that I had a tyop in my previous post where <body> should have been </body> instead. I’ve edited that post to fix the error, and my apologies for any confusion that it let to.