2016-03-12 4 views
0

Я пытаюсь сделать простое приложение для викторины javascript с кнопками radio. Я почти закончил создание приложения, но что, если я хочу добавить вопрос в массив allQuestions, который имеет параметры, не равные 3 (например, 2 или 4). Например, что я могу сделать, чтобы удалить или добавить кнопки radio в зависимости от количества опций, заданных вопросом, например, вопрос 1 имеет только 2 варианта, но 3 radio кнопки & вопрос 2 имеет 4 варианта, но три кнопки radio. Код:Динамически добавлять радиокнопки

var allQuestions = [{ 
 
    question: "Who is the Prime Minister of the United Kingdom?", 
 
    choices: ["David Cameron", "Gordon Brown"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of India?", 
 
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi","Dr.Manmohan Singh"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of America?", 
 
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"], 
 
    correctAnswer: 1 
 
    }, 
 

 
    { 
 
    question: " Who averaged one patent for every three weeks of his life?", 
 
    choices: ["Thomas Edison", "Tesla", "Einstein"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "What continent is cut into two fairly equal halves by the Tropic of Capricorn?", 
 
    choices: ["Africa", "South America", "Australia"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "What explorer introduced pigs to North America?", 
 
    choices: ["Christopher Columbus", "Galileo", "Mussorie"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "What F-word is defined in physics as a “nuclear reaction in which nuclei combine to form more massive nuclei”? ", 
 
    choices: ["Furnace", "Fusion", "Fission"], 
 
    correctAnswer: 1 
 
    }, 
 

 
    { 
 
    question: "What was the first planet to be discovered using the telescope, in 1781?", 
 
    choices: ["Uranus", "Jupiter", "Mars"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "Who is the chief minister of West Bengal, India?", 
 
    choices: ["Buddhadev Bhattacharya", "Jyoti Basu", "Mamta Banerjee"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "Which is the fastest growing religion in the world?", 
 
    choices: ["Islam", "Christianity", "Hinduism"], 
 
    correctAnswer: 0 
 
    } 
 
    /* 
 
    \t { 
 
    \t \t question: "Who is the Prime Minister of America?", 
 
    \t \t choices: ["Donald Trump","Barack Obama","Hilary Clinton"], 
 
    \t \t correctAnswer:1 
 
    \t }, 
 

 
    \t { 
 
    \t \t question: "Who is the Prime Minister of America?", 
 
    \t \t choices: ["Donald Trump","Barack Obama","Hilary Clinton"], 
 
    \t \t correctAnswer:1 
 
    \t }, 
 

 
    \t { 
 
    \t \t question: "Who is the Prime Minister of America?", 
 
    \t \t choices: ["Donald Trump","Barack Obama","Hilary Clinton"], 
 
    \t \t correctAnswer:1 
 
    \t }, 
 

 
    \t { 
 
    \t \t question: "Who is the Prime Minister of America?", 
 
    \t \t choices: ["Donald Trump","Barack Obama","Hilary Clinton"], 
 
    \t \t correctAnswer:1 
 
    \t }, 
 

 
    \t { 
 
    \t \t question: "Who is the Prime Minister of America?", 
 
    \t \t choices: ["Donald Trump","Barack Obama","Hilary Clinton"], 
 
    \t \t correctAnswer:1 
 
    \t } \t */ 
 
]; 
 

 

 
$(document).ready(function() { 
 
    var currentquestion = 0; 
 
    var correctAnswers = 0; 
 
    $("#container").hide(); 
 
    $('#start').click(function() { 
 
    $("#container").fadeIn(); 
 
    $(this).hide(); 
 
    }); 
 

 
    $(function() { 
 
    $("#progressbar").progressbar({ 
 
     max: allQuestions.length - 1, 
 
     value: 0 
 
    }); 
 
    }); 
 

 
    $('#question').html(allQuestions[currentquestion].question); 
 
    $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
    $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
    $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 

 
    $("#next").click(function() { 
 
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
     correctAnswers++; 
 
    }; 
 
    currentquestion++; 
 
    $(function() { 
 
     $("#progressbar").progressbar({ 
 
     value: currentquestion 
 
     }); 
 
    }); 
 
    if (currentquestion < allQuestions.length) { 
 
     $('#question').html(allQuestions[currentquestion].question); 
 
     $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
     $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
     $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 
     if (currentquestion == allQuestions.length - 1) { 
 
     $('#next').html("Submit"); 
 
     //$('#next').off("click"); 
 
     $('#next').click(function() { 
 
      $("#container").hide(); 
 
      $("#result").html("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers * 100/(currentquestion)) + "%").hide(); 
 
      $("#result").fadeIn(1500); 
 
     }); 
 

 
     } 
 

 
    }; 
 
    }); 
 
});
.button { 
 
    display: inline-block; 
 
    padding: 1em; 
 
    background-color: #79BD9A; 
 
    text-decoration: none; 
 
    color: white; 
 
} 
 
body { 
 
    text-align: center; 
 
} 
 
.ui-widget-header { 
 
    background-image: none !important; 
 
    background-color: #FF7860 !important; //Any colour can go here 
 
} 
 
label { 
 
    display: inline-block; 
 
    /*text-align: center;*/ 
 
} 
 
h3, 
 
#next { 
 
    text-align: center; 
 
    display: inline-block; 
 
    border-radius: 20%; 
 
} 
 
input[name="option"] { 
 
    float: left; 
 
} 
 
#form div { 
 
    margin: auto; 
 
    max-width: 205px; 
 
} 
 
#progressbar { 
 
    margin: auto; 
 
    margin-top: 20px; 
 
    float: none; 
 
    width: 50%; 
 
    /*height: 100%;*/ 
 
} 
 
#container { 
 
    text-align: center; 
 
} 
 
span { 
 
    margin: 5em; 
 
    padding: 3em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" /> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
 
<body> 
 
<h1>Quiz</h1> 
 
<a href="#" id="start" class="button">Let's Begin</a> 
 
<br/> 
 
<div id="container"> 
 
    <h3 id="question"></h3> 
 
    <form id="form"> 
 
    <div> 
 
     <input type="radio" name="option" value="0" id="option0" checked> 
 
     <label for='option0'></label> 
 
     <br/> 
 
    </div> 
 
    <div> 
 
     <input type="radio" name="option" value="1" id="option1"> 
 
     <label for='option1'></label> 
 
     <br/> 
 
    </div> 
 
    <div> 
 
     <input type="radio" name="option" value="2" id="option2"> 
 
     <label for='option2'></label> 
 
     <br/> 
 
    </div> 
 
    </form> 
 

 
    <br/> 
 
    <a href="#" id="next" class="button">Next</a> 
 
    <br/> 
 
    <div id="progressbar"></div> 
 
</div> 
 
<div id="result"></div> 
 
</body>

Вот JSFiddle

+0

@JacobGray, мои плохие ... но они все равно должны быть фиктивными вопросами. Я буду менять все вопросы, как только закончите с кодом. – Rashid

+0

Можете ли вы добавить более подробную информацию по своему вопросу, в частности о проблеме? –

+0

@JacobGray Я отредактировал вопрос, надеюсь, теперь это имеет больше смысла. – Rashid

ответ

1

Try таким образом: я редактировал jsfiddle https://jsfiddle.net/kingychiu/vLwjzx8o/16/

function setupOptions(){ 
     $('#question').html(allQuestions[currentquestion].question); 
     var options = allQuestions[currentquestion].choices; 
     var formHtml =''; 
     for (var i = 0; i < options.length; i++){ 
     formHtml += '<div><input type="radio" name="option" value="'+i+'" id="option'+i+'"><label for="option'+i+'">'+allQuestions[currentquestion].choices[i]+'<br/></label><br/></div>'; 
     } 
     $('#form').html(formHtml); 
} 

Кстати, для динамической привязки данных с помощью ui я предлагаю вам использовать Angular js, ng-repeat, которые улучшают код.

+1

@nign, что сработало спасибо .. Я знаю, что код довольно уродлив и, кроме того, дублирован, но я учусь. Я - абсолютный новичок. Это мой первый кусок кода, который сам взял на себя три дня. Тем не менее, чтобы узнать Угловое, js .. – Rashid

+0

@ nign..I признаю вашу честную обратную связь .. – Rashid

+0

@Rashid Я не говорю, что ваш код уродлив, ваш исходный код в jsfiddle отличен. Я просто не хочу помещать HTML-код в строку JS (трудно отлаживать, находить отсутствующие теги и т. Д.). С другими библиотеками, такими как угловые, мы можем избежать такой «HTML-строки». – nlgn

0

Вы можете попробовать для каждого цикла:

$(allQuestions).each(function(index) { 
    // Loop your entirely div + input + label and use the index to determine the question 
    /* 
    <div> 
     <input type="radio" name="option" value="0" id="option0" checked> 
     <label for='option0'></label> 
     <br/> 
    </div> 
    */ 
    // Increment current question or use index 
}); 
Смежные вопросы