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!");
}