最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the id of input on keyup - Stack Overflow

programmeradmin2浏览0评论

I have an input box...

<input type="text" id="search_member" onkeyup="lookup(this.value);">

When I type in the field, it will go to function lookup(). From there I want to get the id of this input. I tried...

var This_id = $(this).attr("id");

but this won't work. Any suggestions on how I can get the id?

I have an input box...

<input type="text" id="search_member" onkeyup="lookup(this.value);">

When I type in the field, it will go to function lookup(). From there I want to get the id of this input. I tried...

var This_id = $(this).attr("id");

but this won't work. Any suggestions on how I can get the id?

Share Improve this question asked Mar 5, 2012 at 23:14 JoeJoe 1,6357 gold badges26 silver badges34 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 11

Because you are passing this.value to your lookup() function. It's better to pass this to your function and then use arg.value to get the value and arg.getAttribute('id') for the id

<input type="text" id="search_member" onkeyup="lookup(this);">

function lookup(arg){
 var id = arg.getAttribute('id');
 var value = arg.value;
 // do your stuff
}

Get rid of onkeyup="lookup(this.value);

<input type="text" id="search_member">

and then use

$(function(){
    $("#search_member").keyup(function(e){
        var This_id = $(this).attr("id");
    });
};
$(document).keyup(function(e) {
    if (e.currentTarget.activeElement != undefined) {
     var id = $(e.currentTarget.activeElement).attr('id');
  }
});

The problem there is you're not passing the element in, you're passing the value. You need to change it to this:

<input type="text" id="search_member" onkeyup="lookup(this);">

Then the rest of your code should work fine.

why dont you give the function lookup the THIS?

 lookup(this);

then u can also use the code you suggested

To get the id you should use this.id not this.value. I hope it work with you

发布评论

评论列表(0)

  1. 暂无评论