Get the input selector using this

67 views Asked by At

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.

2

There are 2 answers

1
Chava Geldzahler On BEST ANSWER

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)"/>

0
Phani Kumar M On

Another method:

$(document).ready(function () {
    var inputs = document.querySelectorAll("input[type=text]");
    for (i = 0; i < inputs.length; i++)
        inputs[i].addEventListener("focusout", function () { validate(this); });
});

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