1

I'm trying to get the value of a hidden input from a form in my HTML, using javascript. But after trying several different ways to get the value, it always says in console(firebug) that the variable is null.. heres the javascript:

var mcq_test = form.mcq_test.value;
console.log("mcqid=" + mcq_test)
var mcq_num_questions = form.mcq_num_questions.value;
console.log("totalquestions=" + mcq_num_questions)
var x = 1;
var send = [];
send.push("mcq_test=");
send.push(mcq_test);

console.log("Send: " + send);

// have commented out the bits below...just go through them carefully looking at the string functions, put them in the send += (SRING 1 + STRING 2 + ...) format

for (var x = 1; x <= mcq_num_questions; x++) {
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(x); // mcq_question_id$ctr the question numer
console.log("2 = " + questionid);
var mcqid = form.questionid.value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(x); // mcq_question$ctr the questions chosen answer
var chosenanswer = form.answer.value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer,equal); // "&mcq_question$ctr="
if (x = 1) { send.push(questionide, mcqid, answere, chosenanswer); }
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
} 

Console:

[04:08:00.328] TypeError: questionID is null 
[04:08:00.327] My new function
[04:08:00.327] mcqid=566
[04:08:00.327] totalquestions=3
[04:08:00.327] Send: mcq_test=,566
[04:08:00.328] 1 = mcq_question_id
[04:08:00.328] 2 = mcq_question_id1

Form:

echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";

-- Update

Answer found! Turns out, you can't use the syntax document.getElementByID() or form.variable.value; and put a variable in there, it has to be a string or written like this:

form[variable].value;

I didn't find an equivalent for getElementById but the form method works for me.

4

2 に答える 2

0

これを使うとき

echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";

入力タイプを作成する前に、'$questionID' が null でないことを確認してください

これを使ってテスト

echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"questions\" form=\"SubmitTest\" />";
于 2012-12-29T04:41:47.247 に答える
0

DOM にアクセスする前に、DOM がロードされていることを確認する必要があります。HTML の後に Javascript を配置するか、変数定義をトリガーするイベントをセットアップします。

于 2012-12-29T04:20:50.193 に答える