1

When I try to get the active element in javascript (document.activeElement.tagName), it keeps returning BODY. The input element was created with jquery.

Here's the situation: On page load, I created an input box via jquery. (standard class, dynamic id)

on a button click, I want to test if that input box is selected

Thanks for the help

Trevor Newhook
  • 889
  • 1
  • 11
  • 29

2 Answers2

4

document.activeElement returns the currently focused element. When there is no focused element, the active one is the page's body.

When you click button, the textbox no longer has the focus, so the body element is always returned.

See more at: https://developer.mozilla.org/en-US/docs/DOM/document.activeElement

webprogrammer
  • 792
  • 15
  • 26
phnkha
  • 7,782
  • 2
  • 24
  • 31
0

You'll have to keep track of the last selected item by monitoring which one was clicked on last.

The following script should accomplish what you're looking for.

jsFiddle

JS

$('body').append(
  //Dynamic Inputs being added
  $('<input />', { 'id':'test', 'type':'text'})
).append(
  //Dynamic Inputs being added
  $('<input />', { 'id':'test2', 'type':'text'})
).on('click', 'input[type="text"]', function(e){
  //Keep track of the last selected input
  $('.lastSelected').removeClass('lastSelected'); 
  $(this).addClass('lastSelected'); 
}); 

//Get the last selected input from the page on a button click
$('#mybutton').click(function(e){
  var items = $('.lastSelected')
  if(items.length > 0){
    alert($('.lastSelected').attr('id')); 
  }
}); 

HTML

<input id='mybutton' type='button' value='Click Me' />
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100