1

Here is part of the function:

function updateResponse(question, answer) {
    questionId = 'q'+question;
    document.forms[0].questionId.value = answer;

Calling the function with something like:

<td onClick='javascript:updateResponse(1, 1);'>

The form element I want it to update looks something like:

<input type='hidden' name='q1' value='' />

Using Firefox web console I get:

TypeError: document.forms[0].questionId is undefined

Thanks!

UPDATE: Found this after much googling and it works. Still seems like there may be a more graceful way to achieve this though?

eval(\"document.forms[0].\"+questionId+\".value = answer;\");
2
  • You do not need the javascript: prefix there.. Commented Mar 28, 2013 at 5:52
  • removed that, thanks. still the same error message. Commented Mar 28, 2013 at 5:55

1 Answer 1

2

If you're sure there's an input in the form that has the name questionId:

document.forms[0][questionId].value

And you should use var to avoid global variable:

var questionId = 'q' + question;

Sign up to request clarification or add additional context in comments.

6 Comments

questionId is the name of the variable. It's value should be q1 or similar.
Thanks. Added var but still getting the same error. To be clear, I want javascript to substitute the word questionId with it's value 'q1'. It looks to me like it is trying to find a form element called 'questionId'. It needs to find 'q1', 'q2', 'q3' etc depending on the value of variable 'questionId'.
Have you even tried the first JavaScript line I answered, e.g.: document.forms[0][questionId].value = answer;? That would satisfy your need whatever value the questionId holds.
Yes, sorry I should have posted the result. When using document.forms[0].[questionId].value = answer; I get: SyntaxError: missing name after . operator
You've added an extra '.'.
|

Your Answer

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.