Search code examples
javascriptjquery-eventsjquery-focusout

Get the input selector using this


I have set of input fields which are generated dynamically, hence I can't use an ID. For each of the input fields I have a focusout method which validates the value input by the end user.

If the validation fails, I would like to clear the value of the input and bring back the focus to the same input. When I tried to use this keyword scope seems to be set to the windows rather than the input control.

Input fields screenshot:

Input fields screenshot

function validate(reg){
debugger;
if(isNaN(reg)==false){
    return;
}
else
{
    alert("The field should contain number");
    $(this).val(""); //clear the value
    $(this).focus();
}
}

In the above code, this keyword doesn't seem to work.


Solution

  • Pass the event to your validate() function, and then you can use event.target to target the input element.

    function validate(reg, e){
    debugger;
    if(isNaN(reg)==false){
        return;
    }
    else
    {
        alert("The field should contain number");
        $(e.target).val(""); //clear the value
        $(e.target).focus();
    }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input onfocusout="validate(this.value, event)"/>
    <input onfocusout="validate(this.value, event)"/>
    <input onfocusout="validate(this.value, event)"/>