Reputation: 67
I'm actually doing up a questionnaire website for my own purpose. I manage to do a loop but I suppose my sequence of java script is wrong. Below is my code:
<script>
$(document).ready(function()
{
var string ="";
for(var i=2;i<12;i++){
string +="<option value='"+i+"'>"+(i-1)+"</option>";
console.log('test');
}
$("#select-question-type").change(function(evt)
{
var selected = $(this).val();
if (selected == "1"){
$(".show-qn").show();
$(".show-check").hide();
} else if(selected == '2') {
$(".show-check").hide();
$(".show-qn").hide();
} else if(selected == '3'){
$(".show-check").show();
$(".show-qn").hide();
}
}).change();
$("#total_qn_number").html(string);
$("#total_qn_number").change(function(e){
console.log("changed");
var counter = $(this).val();
var appendString = "";
console.log(counter);
for(var x=1;x<counter;x++){
appendString+='<br />Question '+x+':<br /><textarea name="question' +x+'" placeholder="Type your question"></textarea><br /><div class="show-qn"><label></label>A1:<input type="text" name="answer1' +x+'" placeholder="Type your 1st option" /><br /><label></label>A2:<input type="text" name="answer2' +x+'" placeholder="Type your 2nd option" /><br /><label></label>A3:<input type="text" name="answer3' +x+'" placeholder="Type your 3rd option" /><br /><label></label>A4:<input type="text" name="answer4' +x+'" placeholder="Type your 4th option" /></div><div class="show-check"><input type="text" name="cb1' +x+'" placeholder="Type your 1st option" /><br /><input type="text" name="cb2' +x+'" placeholder="Type your 2st option" /><br /><input type="text" name="cb3' +x+'" placeholder="Type your 3st option" /><br /><input type="text" name="cb4' +x+'" placeholder="Type your 4st option" /><br /><input type="text" name="noOfCorrectAns' +x+'" placeholder="Type down the no of correct ans." /></div>';
}
$("#container").html(appendString);
});
});
</script>
It actually works pretty well but the problem lies with the show and hide. Whenever I choose my select box option, it actually "restart" the whole js itself removing all the .show and .hide functions and I've to re-click the option box for it to display normally. The picture is as below:
Before:
After:
And IF i re-choose my number of question, the 'before' picture appear again which will make user irritated. Is there a way to make it stay like 'After' even if I re-choose my option?
UPDATE: Link to fiddle: jsfiddle.net/537vh
Upvotes: 1
Views: 112
Reputation: 348
IS this what you are looking for: http://jsfiddle.net/m69XP/2/
I put this in a function that gets called on change of both select boxes
$("#select-question-type").change(function(evt)
{
var selected = $(this).val();
if (selected == "1"){
$(".show-qn").show();
$(".show-check").hide();
} else if(selected == '2') {
$(".show-check").hide();
$(".show-qn").hide();
} else if(selected == '3'){
$(".show-check").show();
$(".show-qn").hide();
}
else{
$(".show-check").hide();
}
}).change();
Upvotes: 1