0

I have a few textboxes with the same class, and want to assign a method on the focus event for them all. This does not work:

$('.postal').onfocus = setLeft();

In dev-tools the controls' class is 'postal x-form-text x-form-field', so would that make the above jquery not work?

5 Answers 5

3

This should work -

$('.postal').on('focus',setLeft);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That worked straight away. My jquery is very limited: do you have any web resources I can use to sharpen up?
@callisto - they have excellent documentation. for example, if you would have googled jquery on focus, the .focus() page would be tops. from an experimenting standpoint, the .on() selector can be used for any on event ... onhover, onclick, etc. you can even bind multiple handlers in a single .on() declaration!
1

Not trying to steal any thunder, just providing additional information about the use of the .on() handler.

You can combine it with several other handlers to consolidate code and minimize DOM impact! For example:

$('.postal').on({
    focus:setLeft, // predefined functions can be used as long as there are no parameters passed
    click:function(){
        alert('clicked');
    },
    blur:function(){
        hideMe($(this)); // for functions that pass in parameters, encase them in separate functions
    }
});

This is an incredibly powerful and efficient way to utilize .on(), because the DOM is only scraped once. This is better than doing different binds using the shorthand of .focus(), .click(), and .blur(), which would require the DOM being scraped with each binding.

Comments

0

Using jquery:

$('.postal').on('focus',setLeft);

Comments

0

There is a shortcut as well

$('.postal').focus(setLeft);

Comments

0

Well, this is a basic.

You can assign any method in the callback when using jQuery.

Most of times, we use functions this way:

$('.postal').on('focus', function(){ /* Do something */ });

But this is also valid:

$('.postal').on('focus', hello);

function hello(){ alert('hello'); };

So, I think the second way fits your requirement to assign a method for multiple controls with the same class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.