3

We have a lot of inputs in a document.
We want to open a dialog that generates text and puts that in the currently focused input.

The problem is that, when I click a button or anything else to open the dialog that input loses focus. I can't determine which input has to get the generated text.

$("#button").click(function(){
    // something should goes here to prevent stealing inputs focus
});

Is there any solution to prevent stealing focus by that special button?

Jason
  • 15,017
  • 23
  • 85
  • 116
Omid
  • 4,575
  • 9
  • 43
  • 74

3 Answers3

1

You could not use a form button and just use say a <span> make it behave like a button?

UPDATE:

You could use something like

$('span').hover(function(){
    focused_element = $("*:focus").get(0);
});
$('span').click(function(){
    focused_element.focus();
});

Check out my fiddle

Alex
  • 8,875
  • 2
  • 27
  • 44
  • ohh really? hmmm maybe you might need to do as @ggzone, suggests in the comments. – Alex Jan 09 '12 at 11:27
  • doesnt to do with the lost focus ? – e382df99a7950919789725ceeec126 Jan 09 '12 at 11:28
  • input blur will fire before span click – Omid Jan 09 '12 at 11:34
  • @OmidAmraei You worry about the performance of adding a `focus()` handler in my answer, but then use a solution with not only the `*` selector BUT ALSO a `:focus` psuedo selector? I give up. – Rory McCrossan Jan 09 '12 at 11:48
  • @RoryMcCrossan `:focus` selector will run just one time, but `focus` event will run every time that all the inputs will get focus. anyway i use `input[type=text]:focus` instead. i voted up for the solution. – Omid Jan 09 '12 at 11:51
  • this is how you code javascript when you learn jQuery without having any idea about javascript. wtf is $("*:focus").get(0)? Do you mean document.activeElement :d – Semra Jan 16 '15 at 18:48
0

Does your field have a unique ID? If it does, use that ID to set the focus back to the field when the dialog's save/close button is clicked.

Don't worry about having the focus stolen as much as resetting it once you are done.

Jason
  • 15,017
  • 23
  • 85
  • 116
0

My solution would be to handle every focus and save it in focusEle:

$(function () {

    var focusEle;

    $('*').focus(function () {
        focusEle = this;
    });

    $('button').click(function (e) {
        console.log(focusEle);
        var c = confirm('Love the cat :3?');
        $(focusEle).focus();
    });
});

With HTML as:

<input type="text">
<button>Press me!</button>

Example is working: http://jsfiddle.net/76uv7/

Depending on @ggzone idea