-1

I want to make a function that will handle focus for multiple forms. I'm certainly doing something wrong here because it isn't working as expected. Can someone tell me what's wrong?

<a href="#" onclick="x('a','b','')">test</a>
<script type="text/javascript">
function x(xform, xbox, xval) {
 document.xform.xbox.focus();
}
</script>
<input type="text" id="b" name="b" />
asked Nov 14, 2010 at 11:54
4
  • I just tried that but still nothing. Good catch though! Commented Nov 14, 2010 at 11:59
  • Where is the <form>? What do you mean by .focus('c')? Commented Nov 14, 2010 at 12:01
  • Kenny, the focus('c') is a typo. I had alert in there and then tried focus. I'll edit my question. The form is below my input and is named a Commented Nov 14, 2010 at 12:04
  • The input must be in the form, otherwise it does not work in any way. Commented Nov 14, 2010 at 12:07

2 Answers 2

1

Not sure why you need the third value (focus does not take any parameter), but it should look like this:

document[xform][xbox].focus();

DEMO

Explanation: document.xform will access the xform property of document. But document[xform] will access the property taken from the value of xform.

answered Nov 14, 2010 at 12:03
Sign up to request clarification or add additional context in comments.

6 Comments

Felix, I'm still having a problem with passing in a value. Is there something special I must do?
@jim: I don't know what you mean, do you want to set a value for the input field?
Yes, exactly then focus it after the value has been set.
I thought I could could just follow the focus example but it doesn't work.
@jim: It depends what kind of form elements you are dealing with. For an input element, you do element.value = newValue, so you could do document[xform][xbox].value = xval
|
0

You can use bracket notation as Felix has...however IDs should be unique in a page, so just this would work:

function x(id) {
 document.getElementById(id).focus();
}

Then in your code use the id that your <input> already has:

<a href="#" onclick="x('b')">test</a>
answered Nov 14, 2010 at 12:05

1 Comment

Thank you, Nick. I will make the adjustments and this is also good to know.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.