Miguel Flores Miguel Flores - 1 month ago 5
Javascript Question

How to get input value without id

what I want to do is something like when user finished typing my app shows a message of the value typed in that input, I will have a lot of inputs so it's not an option doing by selecting input ID, so how can I solve this problem? What I'm trying to do is selecting

$(this).value
but I only get "undefinied", here is an example code of what I'm trying to do



var timer = null;
$(document).ready(function () {
$('input').keydown(function (event) {
clearTimeout(timer);
timer = setTimeout(validarType, 1000)
});


});
function validarType() {
var xd = $(this).value;
alert(xd);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text"/>




Answer

Your code isn't working for 2 reasons

this isn't the same this as it was when your handler was called - because you're calling this function from within a timeout.

$(this) is a jQuery object - there is no value attribute

Correct code:

var timer = null;
$(document).ready(function () {
    $('input').keydown(function (event) {
        clearTimeout(timer);
        timer = setTimeout(validarType.bind(this), 1000) //bind the existing context
    });
});
function validarType() {
    var xd = this.value; //this is now a regular DOM element - and has a value attribute
    alert(xd);
}  
Comments