Let's begin with the usage of your regex, you should be doing it like this:
var inputString = document.getElementById('priceGST').value;
var regex = /^[0-9]*\.?[0-9]*$/;
var valid = regex.test(inputString);
So this should work just fine for you:
function pointAndNumbersOnly(inputString)
{
var regex = /^[0-9]*\.?[0-9]*$/;
var valid = regex.test(inputString);
return valid;
}
var inputString = document.getElementById('priceGST').value;
var valid = pointAndNumbersOnly(inputString);
There are other options though:
function pointAndNumbersOnly(inputString)
{
var regex = /^[0-9]*\.?[0-9]*$/;
var valid = regex.exec(inputString);
return valid;
}
var inputString = document.getElementById('priceGST').value;
var valid = pointAndNumbersOnly(inputString);
Let's make your function even better by only requiring elements to be pushed down, not their values:
function pointAndNumbersOnly(inputElement)
{
var inputString = inputElement.value;
var regex = /^[0-9]*\.?[0-9]*$/;
var valid = regex.test(inputString);
return valid;
}
var inputElement = document.getElementById('priceGST');
var valid = pointAndNumbersOnly(inputElement);
Now another matter:
Using html-attributes such as onkeypress
, click
, etc... is bad practice since we want to separate our HTMLand JavaScript. Besides, onkeypress
is a problem maker to begin with because it doesn't always do what you think it does. It's better to use change
, keyup
and keydown
to detect changes.
Instead of using onkeypress="return pointAndNumbersOnly(this.id);
we want to use event delegation to detect changes in the dom, using our new change events:
function pointAndNumbersOnly(inputElement)
{
var inputString = inputElement.value;
var regex = /^[0-9]*\.?[0-9]*$/;
var valid = regex.test(inputString);
return valid;
}
inputElement.addEventListener("change, keyup, keydown", function(e)
{
var inputElement = document.getElementById('priceGST'); // Makes more sense to use this
var valid = pointAndNumbersOnly(inputElement );
// ...
});
You can also add event listeners to a set of elements by referencing to their class.
Finally:
Make sure the JavaScript is defined AFTER your DOM is ready, that is, make sure the JavaScript is added at the bottom of your body so that the HTML exists OR you have functionality such as jQuery's .ready function, that detects when the DOM is loaded and the JavaScript within is allowed to execute, otherwise it won't know the HTML ids' such as id="priceGST"
.
If you define your JavaScript and try to reference HTML ids' then you'll see that they are undefined
, or just null
, because they don't exist at that specific point.