0

I will first say, it has been a couple years since I have written Greasemonkey/Userscripts last and I am a bit rusty with my JavaScript, and this should be a simple question.

I am trying to detect if a specific textbox has focus. (I plan on running a script when a specific box has focus and the user presses the enter key.) My issue is that the site does not have an ID tag for the textbox, only a name tag <input type="text" size="20" value="" name="Category_Product_Search"></input> and nearly all of the tutorials that I see requires the textbox to have an ID tag.

Thank you,

Charles

CampSoup1988
  • 139
  • 6
  • 21

2 Answers2

2

You could simply test for the focused-element on its focus event, though I'd advise binding to a closer ancestor element that contains all the elements you want to test, rather than the body I'll use in my demonstration code:

function elementIs (e){
    var target = e.target,
        targetTagName = target.tagName.toLowerCase();
    /* Using a switch () rather than if/else if/else, for simplicity and
       ease of extension to other focusable element-types, though adjust
       to whichever technique you're more comfortable with:
    */
    switch (targetTagName){
        case 'input':
            if (target.name === 'Category_Product_Search') {
                // do something, it's an input and has the right name:
            }
    }
}
document.body.addEventListener('focus', elementIs, true);

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

If the order of the input boxes is fixed, you can use form = document.getElementsByTagName('input'). And then you could simply use the index number for the required text box.

If the name tag is unique then you can also use form.elements["name"] after that.

gat
  • 2,872
  • 2
  • 18
  • 21