Commas in INPUT textfields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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