s3v3n
s3v3n

Reputation: 8446

Attach event listener to elements of a given class

So this may be easy but I can't get it work. I have 3 text inputs of filter class. What I want is bind a function search() to onkeypress event. I know I can write it manually to every input like this onclick="search()" but I don't want to use inline things, just prototype functions. My current code is:

<input type="text" class="filter" id="id"/>
<input type="text" class="filter" id="title"/>
<input type="text" class="filter" id="quant"/>

and

Event.observe('.filter', 'keypress', function(){ // <<< this don't work :(
    alert('yey!');
});

Upvotes: 0

Views: 425

Answers (1)

user113716
user113716

Reputation: 322492

I'm not too familiar with prototypejs, but I believe you can do this:

Example: http://jsfiddle.net/patrick_dw/yAj3A/

$$('.filter').invoke('observe','keypress', function(){
    alert('yey!');
});

EDIT: Or if you wanted to use a named function, you can do that too.

Example: http://jsfiddle.net/patrick_dw/yAj3A/1/

function search(){
    alert('yey!');
}

$$('.filter').invoke('observe','keypress', search);

Upvotes: 4

Related Questions