0

I have a form where a user needs to input time entries for a date range. I need to validate what they're inputting so I was hoping I could create one function to simply validate a value to make sure it's numeric. Then tie that function to each textbox that has a css class of hourmin. I think I'm headed in the right direction below but I'm not sure how to finish it.

$(".hourmin").change(function () {
    //apply this validation call to the textbox which has .hourmin class
});
geoff swartz
  • 5,437
  • 11
  • 51
  • 75

5 Answers5

0

You can use $(this) to get the current textbox as a jQuery object and val() method for getting its value.

Giorgi
  • 30,270
  • 13
  • 89
  • 125
0

See Validate decimal numbers in JavaScript - IsNumeric() For a long discussion on how to determine if a value is numeric. To get the value:

$(this).val();
Community
  • 1
  • 1
Plaudit Design
  • 1,156
  • 8
  • 16
0

Define a css class invalid to highlight the invalid field, then use something akin to this:

$(".hourmin").change(function () {
    $(this).toggleClass('invalid', validate($(this).val()));
});

where validate() does your validation and returns a boolean. Have a look at Validate decimal numbers in JavaScript - IsNumeric() for a possible implementation of this.

Community
  • 1
  • 1
tKe
  • 560
  • 2
  • 9
0

Html:


Date:<input type="text" id="day" size="10" class="date" /> <input type="text" id="month" size="10" class="date" /> <input type="text" id="year" size="10" class="date"/>

jQuery:


$('.date').change(function(){
    var id=$(this).attr("id");
    var val = $(this).val();
    switch(id)
    {
        case "day":
            //validate day
            break;
        case "month":
            //validate month
            break;
        case "year":
            //validate year
            break;
    }
});

hope this helps

Prashant Lakhlani
  • 5,758
  • 5
  • 25
  • 39
0

Thanks, it was the $(this) that I was missing. Here's the final code in case it helps anyone else.

 $(document).ready(function () {
        $(".hourmin").change(function () {
            numbers = $(this).val();
            $(this).val(numbers.replace(/[^\d]+/g, ''));
        });
    });
geoff swartz
  • 5,437
  • 11
  • 51
  • 75