Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created April 28, 2019 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anjanesh/18e0eebe4415241952f42c9a1613943e to your computer and use it in GitHub Desktop.
Save anjanesh/18e0eebe4415241952f42c9a1613943e to your computer and use it in GitHub Desktop.
Commas in INPUT textfields
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="container">
<form id="frm" class="form" action="" method="post">
<div>
<div>
<label for="Marketing_Expense" style="display:inline;">Enter your initial monthly marketing expense</label>
</div>
<div>
<span style="margin-top:-2px">$</span>
<input type="text" name="Marketing_Expense" id="Marketing_Expense" class="dollar" maxlength="25" value=""/>
</div>
</div>
<button type="submit" id="submit">Submit</button>
</form>
</div>
<script>
/* http://stackoverflow.com/questions/2632359/can-jquery-add-commas-while-user-typing-numbers */
$('input.dollar').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/,/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
$(document).ready(function()
{
$('input.dollar').val(function(index, value)
{
return value
.replace(/,/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
$('.form').on("submit", function()
{
$('input.dollar').val(function(index, value)
{
return value.replace(/,/g, '');
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment