tags:

views:

17

answers:

2

Hi How do i add event to multiple field of same form.

In Following code i want to add keypress event to userName also.

$("#existingUserForm :input[name='userPassword']").keypress(    
        function(e) {       
        if(e.which == 13) { 
            processLogin();
        }
    }); 
+1  A: 

You can use the add() method to add elements to your selection:

$('#existingUserForm :input[name=userPassword]')
    .add('#existingUserForm :input[name=userName]')
    .keypress(function() { ...

You can also chain multiple selectors inside one $() clause by separating them with commas, but the add() method is usually better for readability.

You can also use filter():

$('#existingUserForm input').filter(function() {
    var name = $(this).attr('name');
    return name == 'userPassword' || name == 'userName';
}).keypress(function() { ...

Easiest method would be to give the elements the same classname, then your selector would simplify to:

$('#existingUserForm .checkField').keypress(function() {...

...given that your inputs are something like this:

<input name="userName" class="checkField" />
<input name="userPassword" class="checkField" />
Tatu Ulmanen
+2  A: 
$("#existingUserForm :input[name='userPassword'], #existingUserForm :input[name='userName'] ").keypress(    
     function(e) {       
        if(e.which == 13) { 
            processLogin();
        }
 });

Read in the documentation about multiple selectors.

Felix Kling