0

I am checking numeric value for one textbox like this:

function validateNumeric() {
    var old = document.getElementById("tbNum").value;
    var new = old_val.replace(/^\s+|\s+$/g,"");
    var validChars = '0123456789'; 

    for(var i = 0; i < new.length; i++){ 
        if(validChars.indexOf(new.charAt(i)) == -1){
        alert('Please enter valid number');
        return false; 
        }
    }
    document.getElementById("tbNum").value = new;
    return true; 
}

I want to use the same function and check numeric value for other text boxes that requires numeric value. How can I pass value of tbID, tbDiscID, as well as above and return true before submitting the form.

Mac
  • 1,632
  • 9
  • 15
Henry Ii
  • 17
  • 1
  • 5
  • I would recommend using jQuery with something like what posted on [enter link description here][1] [1]: http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Emmanuel N Sep 30 '11 at 18:13
  • A simpler and probably faster way to check if a value is numeric: `val.match(/^\d+$/)` (Where val is the variable you want to check) – anroesti Sep 30 '11 at 18:21

2 Answers2

0

I am not sure what you mean by tbId and tbDiscID, but to do this in plain JavaScript, you can generalize this solution by traversing JavaScript's arguments object, which lets you pass in any variable number of arguments to your function. This will help you take in the IDs you need. Your new solution would look something like the following:

function validateNumeric() {
    for (var arg in arguments) {
        var id = arguments[arg];
        var old = document.getElementById(id).value;
        var new = old_val.replace(/^\s+|\s+$/g,"");
        var validChars = '0123456789'; 

        for(var i = 0; i < new.length; i++){ 
            if(validChars.indexOf(new.charAt(i)) == -1){
            alert('Please enter valid number');
            return false; 
            }
        }
        document.getElementById(id).value = new;
        return true;
    } 
}

Then invoke it like:

validateNumeric("myTextbox1", "myTextbox2", ..., "myTextboxN");

Where myTextBox1 ... myTextBoxN are the IDs of your textboxes.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0

use parameter for the function, for using it on different elements

validateNumeric(value) {

use the onsubmit parameter on the form tag to call a validation

<form name="myForm" action="dosomething.php" onsubmit="return validateForm()"

write your validate function with calls for all elements

function validateForm() {
   if (!validateNumeric(document.getElementById("tbNum"))) {
      return false;
   }
   ...
   return true;

would be one way..

edit
forgot the check within the validateForm method