Ninjin
Ninjin

Reputation: 181

How to get last focused field?

This is my HTML code :

<input type="button" value="1000" onclick="myFunc(this.value)" />
<input type="button" value="2000" onclick="myFunc(this.value)" />
<input type="button" value="3000" onclick="myFunc(this.value)" />
<input type="button" value="4000" onclick="myFunc(this.value)" />

<input type="textbox" value="0" name="myTextbox1" />
<input type="textbox" value="0" name="myTextbox2" />

and here is JS :

function myFunc(value){
    if($('[name=myTextbox1]').is(':focus')){
         var prevVal = $('[name=myTextbox1]').val();
         $('[name=myTextbox1]').val(parseInt(prevVal) + parseInt(value));
         $('[name=myTextbox1]').focus();
    }else if($('[name=myTextbox2]').is(':focus')){
         var prevVal = $('[name=myTextbox2]').val();
         $('[name=myTextbox2]').val(parseInt(prevVal) + parseInt(value));
         $('[name=myTextbox2]').focus();
    }
}

I need to add clicked buttons value to focused textbox value. When i click button the focus is on button, so can i get last focused textbox?

Thank you ..

Upvotes: 0

Views: 1505

Answers (3)

Zakir
Zakir

Reputation: 1

<input type="textbox"  value="1"  class="is_focus"/>
<input type="textbox"  value="2"  class="is_focus"/>
<input type="textbox"  value="3"  class="is_focus"/>
<button class="get_data">Click</button>

$(function() {
        var focus_variable = null;

        $('body').on('focus', '.is_focus', function(e) {
            focus_variable = $(this);
        });

        $('body').on('click', '.get_data', function(e) {
            var focus_data =  focus_variable.val();
            console.log(focus_data);
        });

    });

Upvotes: 0

Erik Blessman
Erik Blessman

Reputation: 693

var lastFocused = null;

<input type="textbox" 
    value="0" 
    name="myTextbox2"
    onfocus="lastFocused=this;"/>

I apologize if there are syntax errors, I'm submitting this from my phone, so I do not have a good way to test it.

Upvotes: 2

Erik Blessman
Erik Blessman

Reputation: 693

Create a variable for lastFocused and set it in an onFocus event handler for each text box

Upvotes: 0

Related Questions