开发者

Javascript how to move variables with event-listener?

I have the following function that writes a multi-choice question from JSON object.

First, is the event-listener creation here "legal"? And if so, I want the function executed by the listener (validate) to get the number of the form on which "submit" was clicked, and the number of the check-box that was checked. How can I do that? thanx.

function writeQuestions() {

len = questions.qestion.length;
for (var i = 0; i < len; i++) {

        answerRdy = [];
        qestionRdy = questions.qestion[i];
        answerRdy[0] = questions.answer[i][0];
开发者_高级运维        answerRdy[1] = questions.answer[i][1];
        answerRdy[2] = questions.answer[i][2];
        answerRdy[3] = questions.answer[i][3];
        divID = "question-" + i;
        formID = "form-" + i;
        CurrentForm = i;

            writeAnswer = [];
            writeAnswer[writeAnswer.length] = ("\n<div id='{0}'>\n<form id='{1}' name='{1}'>\n").format(divID, formID);
            writeAnswer[writeAnswer.length] = ("<b>" + qestionRdy + "</b><br />\n");
        for (n=0; n<=3; n++) {
            writeAnswer[writeAnswer.length] = ("<input type='radio' name='answerTo{0}' value='{1}' /> {2} <br />\n").format(CurrentForm, n, answerRdy[n]);
                }
            writeAnswer[writeAnswer.length] = ("<input type='submit' value='Submit your answer'>\n</form>\n</div><!--{0}-->").format(divID);


        joinQuestion = writeAnswer.join();
            exp = /,/gi;
        fullQuestion = joinQuestion.replace(exp, "");

    $('#container').append(fullQuestion);
    document.forms[i].addEventListener('submit',validate);
}
}


You are probably better off attaching the submit event using jquery submit() so the function would become a part of the form submit event handler

<script type="text/javascript">
$(document).ready(function(){
    $("form").submit(function(){
    alert($(this).attr("id"));
    alert("Checked radio " + $(this).find("input:checked").val())
    //return false if you do not want to submit the form, otherwise comment it out
    return false;
    });
    });

</script>

<form id="{1}">
<input type="radio" name="answer" value=1>
<input type="radio" name="answer" value=2>
<input type="submit" value="submit">
</form>
<form id="{2}">
<input type="radio" name="answer" value=3>
<input type="radio" name="answer" value=4>
<input type="submit" value="submit">
</form>


you should listen on click of submit button and form onclick should return false. Use frameworks like jquery for making these type of functionality.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜