Попытки сбросить форму javascript заставляют форму исчезнуть - PullRequest
0 голосов
/ 20 октября 2010

Я создал форму, которая случайным образом выбирает 12 вопросов T / F из массива из 16, отображает их в случайном порядке и оценивает их все в конце. Проблема в том, что я не могу очистить форму при обновлении. Когда я пытаюсь почти любым методом, форма, вопросы и все исчезают.

Кнопка сброса, однако, работает.

Вот форма:

<script type="text/javascript">
//Define Questions Array
var q = new Array();
    q[0] = "I have fingers";
    q[1] = "I have toes";
    q[2] = "I have gills";
    q[3] = "I have an appendix";
    q[4] = "I can swim";
    q[5] = "I can fly";
    q[6] = "I am a human";
    q[7] = "I own a PC";
    q[8] = "I own a Mac";
    q[9] = "I own a home";
    q[10] = "I own property in Hawaii";
    q[11] = "I speak english";
    q[12] = "I speak Cantonese";
    q[13] = "I have my driver's license";
    q[14] = "I have my pilot's license";
    q[15] = "I am in the military";
//Define Answers Array
var a = new Array();
    a[0] = "True";
    a[1] = "True";
    a[2] = "False";
    a[3] = "False";
    a[4] = "True";
    a[5] = "False";
    a[6] = "True";
    a[7] = "True";
    a[8] = "True";
    a[9] = "False";
    a[10] = "True";
    a[11] = "True";
    a[12] = "False";
    a[13] = "True";
    a[14] = "False";
    a[15] = "False";

var order = 0; //used to count things
var rand; //random number
var nQ = new Array(16); //re-ordered questions
var nA = new Array(16); //matching re-ordered answers
var uA = new Array(12); //user's answers
var x = 1; //counting variable
var s; //counting variable
var score = 0; //user's score

//This function records the user's input
function recordIt(n,TF)
{
    uA[n] = TF;
}

//This function scores the user's input and display's how many they got correct
function scoreIt()
{
for (s in uA)
{
    if ( uA[s] == nA[s])
    {
        score++;
    }
}
alert(score);
}

//This function checks to see if all of the questions have re-ordered
function allX(arr)
{
    var count = 0;
    while ( count != 16)
    {
        if (arr[count] == "X")
        {
            count++;
        }
        else
        {
            break;
        }
    }
    if (count == 16)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//This randomly organizes the questions and answers
while (allX(q) == false)
{
    rand = Math.floor(Math.random()*16)
    if (q[rand] != "X")
    {
        nQ[order] = q[rand];
        nA[order] = a[rand];
        q[rand] = "X";
        a[rand] = "X";
        order++;
    }
}

//This is the actual form that picks the first 12 questions from the nQ (new questions) array
document.write("<form name=oquiz>");
while (x < 13)
{
document.write(x + ". " + nQ[x]);
document.write("<br/>");
document.write("<input type=radio name=\"" + "q" + x + "\" value=\"True\" onClick=\"recordIt(" + x + ",this.value)\"> True");
document.write("<br/>");
document.write("<input type=radio name=\"" + "q" + x + "\" value=\"False\" onClick=\"recordIt(" + x + ",this.value)\"> False");
document.write("<br/>");
x++;
}
document.write("<input type=\"button\" value=\"Reset Form\" onClick=\"this.form.reset()\" />")
document.write("<input type=\"button\" value=\"Score this quiz\" onClick=\"scoreIt()\" />")
document.write("</form>");
</script>

Намеки были бы изумительными. Спасибо!

Ответы [ 2 ]

1 голос
/ 20 октября 2010

чтобы не использовать document.write, вы можете установить все выходные данные в строку, а затем установить тело или элементы innerHTML для этого вывода.

пример: пример jsfiddle

0 голосов
/ 20 октября 2010

А почему вы не просто используете вход с типом сброса?

<input type="reset" />

Проблема, с которой вы столкнулись, заключается в том, что document.write, вероятно, закрывает саму форму, поскольку вы не пишете правильный HTML-код на страницу.

Вы должны просто создать одну строку с разметкой html и записать ее в одну строку.

var str = "<form>";
str += "<input ... />";
str += "</form>";
document.write(str);

еще лучше, научитесь использовать appendChild и createElement .

...