jquery: when i click a div, give focus to a textbox

25.7k views Asked by At
$('.my-button').click(function() {
    $(".my-textbox").focus()
});

Before Jquery 1.4 this used to be the way to call focus to a textbox, now it doesn't work. When I click the button, I want to call focus to the textbox, what i mean by "focus", is that I want the textbox to act like it was just clicked on, so that the user will not have to click on the textbox.

.focus is supposed to do an auto click onto the textbox i want it to, why isn't it working now? it broke in Jquery 1.4. I just need to know how to do it.

3

There are 3 answers

0
sje397 On BEST ANSWER

It still works. See here.

reference: jQuery focus docs

As mentioned there, calling 'focus' on one element may trigger 'blur' on another - and so use 'focusin' instead.

0
Rudu On

Those are class selectors not IDs - not sure if that's relevant, but they're inherently not unique - particularly in the focus function jquery may just plain refuse - try using IDs (and #mybutton, #mytextbox)

Update: The jQuery doc page points out issues with IE:

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers.

0
Andy E On

Your code works fine for me. However, it looks like you're trying to create a clickable label for an input element. If that's the case, there's an existing element named <label> that will do the job for you, no JavaScript required:

<label for="myTextBox">I'm a label, click me</label>
<input type="text" id="myTextBox" />

Example: http://jsfiddle.net/pkk6y/