views:

54

answers:

2

I have an input box that that is part of a form . depending on some circumstances I want to add an Onfocus element to my form but i want to do this using js and only if needed. I have listed the html code below . Can anyone tell me how I can add the onFocus element using js ? thanks

 <input name="associate" id="associate" type="text" size="30" autocomplete="OFF"
onkeyup="return associatejs() "
    onclick="closeassociate()"                
    />

something like onFocus=Blur() inside the input

Hope this makes sense,

+1  A: 

This JavaScript:

document.getElementById("associate").focus();

will put the cursor in your input field. You'll just have to make it happen for your desired circumstances.

KatieK
HTML5 also added an "autofocus" property you can investigate, but as of this writing browser support is limited. You'd still need to define specific logic in your own JS function.
Andy Atkinson
+1  A: 

Assuming you've already got your function Blur() defined somewhere, you could do this using straight up Javascript (there are three different ways to add event listeners, depending on what browser your user is using, so this method will try to first use the W3C method, then the Microsoft method, and then a fallback method (see this quirksmode article for more info on event registration).

var frm = document.getElementById('[the ID of your form]');
if (frm.addEventListener)
{
  frm.addEventListener('focus', Blur, false);
}
else if (frm.attachEvent)
{
  frm.attachEvent('onfocus', Blur);
}
else
{
  frm.onfocus = Blur;
}

Or you could use a Javascript library which will generally abstract that. For example, using Prototype:

frm = $('[the ID of your form]');
frm.observe('focus', Blur);
Daniel Vandersluis