Reputation: 45
I was wondering is this ideal solution to deal with currency in Javascript? Idea is to limit user that he can only write numbers and decimal point in input. This code is mix of answers I found on this site and some of my own.
HTML:
<p><input type="text" class="form-control" id="cijenanovogtroska" onkeypress="return isNumberKey(event)" name="txtChar"></p>
JS File:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) // checks if you press dot on keyboard
{
if ($("#cijenanovogtroska:text").val().includes(".")) // that text wont include first dot, but you will limit every other try
{
return false;
}
if ($("#cijenanovogtroska:text").val() == "") // It checks if this string is empty, so dot cant go on first place
{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) // numbers and dots are possible inputs
{
return false;
}
else
{
return true;
}
}
Addition to this function, in function where you have to do stuff (etc. save data to database) You would have to check that "." is not on last position.
Is there any better implementation to do it than this?:
if (cijena.slice(-1) != ".")
{
//do stuff
}
else
{
alert("You have decimal point on last place!");
}
Upvotes: 1
Views: 295
Reputation: 28236
You could alternatively also use HTML5 validation, see here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="txtChar" pattern="[\d]+([.,][\d]{0,2})?"
placeholder="number with max. 2 digits"
title="enter a valid currency amount #[,.]##" required><br/>
</form>
Simply enter a few test values and press return
.
Upvotes: 1
Reputation: 153
you can easily specify it in the input tag to take type numbers and it will do the same of all this functions like so :-
<input type='number' name='cijenanovogtroska' id='txtChar'>
Upvotes: 0
Reputation: 4272
Why not a regex ?
<input type=“text” pattern=“^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$” />
PS: i just copy pasted the first regex I found if that one does not fill yow needs go to google a look for regex currency
Upvotes: 1