Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created Apr 28, 2019
Embed
What would you like to do?
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