1

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

4

2 回答 2

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\" />";
于 2012-12-29T04:41:47.247 回答
0

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

于 2012-12-29T04:20:50.193 回答