document.getElementById()始终返回null

时间:2012-12-29 04:19:12

标签: javascript getelementbyid

我正在尝试使用javascript从HTML中的表单中获取隐藏输入的值。 但是在尝试了几种不同的方法来获取值后,它总是在控制台(firebug)中说变量为null ..继承人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);
}
} 

控制台:

[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

形式:

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

- 更新

找到答案!事实证明,您不能使用语法document.getElementByID()或form.variable.value;并在其中放置一个变量,它必须是一个字符串或写成这样:

form[variable].value;

我没有找到getElementById的等价物,但是form方法适用于我。

2 个答案:

答案 0 :(得分:0)

在尝试访问DOM之前,您需要确保已加载DOM。将Javascript放在HTML之后或设置事件以触发变量定义。

答案 1 :(得分:0)

使用时

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

在创建输入类型之前,请确保'$ questionID'不为空

使用此测试

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