javascriptjqueryfocusout

focusout event not being triggered on part of the code


I want the focusout event to be triggered on input elements with class="date" and reside in tables with class='datatable', both for elements in the DOM and elements added dynamically. For dynamically added elements (using createElement and appendChild), the following code works successfully:

$('.datatable').on('focusout','tr td input', function(){
    if (this.class == 'date') {
        this.value = dateValid(this.value);
    }
});

However, for elements that are loaded into the DOM, the above code doesn't work. I also tried the code below, but it doesn't work either:

$('.date').focusout(dateValid(this.value));

The HTML for the input elements that are not triggering the focusout event:

<table class="datatable">
    <tr>
        <td>Prospective Effective Date</td>
        <td><input class="date" type="text" name="effectivedate"></td>
    </tr>
    <tr>
        <td>Prospective Expiration Date</td>
        <td><input class="date" type="text" name="expirationdate"></td>
    </tr>
</table>

I'm very new to JavaScript, any help is appreciated!


Solution

  • i think the problem is with the reserved keyword "class":

    if (this.class == 'date') {
     //...
    }
    

    use className

    if (this.className === 'date') {
     //...
    }
    

    if that doesn't fix the issue. you might be appending additional table.datatable elements instead of tr elements inside the existing table. you can solve that by binding the focusout to the document

    $(document).on('focusout','input.date', function(){
     //...
    });