I've created a simple quiz and am storing the users answers in a database. I have access to the answers as json, which looks like this:
{
"form":{
"1":{
"M1_Q1PRE":{
"a1":"a1"
}
},
"2":{
"M1_Q2PRE":{
"a2":"a2"
}
},
"3":{
"M1_Q3PRE":{
"a2":"a2",
"a4":"a4"
}
}
}
}
(question 3 was multi select checkboxes)
I am trying to build a page at the end of the quiz, that will show all the questions, and the chosen answers that the user chose. I want to hard code the final page:
<p>Question One</p>
<ol type="a">
<li>
<label>
<input type="radio" name="M1_Q1PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="radio" name="M1_Q1PRE" value="a2"> answer b
</label>
</li>
</ol>
<p>Question Two</p>
<ol type="a">
<li>
<label>
<input type="radio" name="M1_Q2PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="radio" name="M1_Q2PRE" value="a2"> answer b
</label>
</li>
</ol>
<p>Question Three</p>
<ol type="a">
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a2"> answer b
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a3"> answer c
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a4"> answer d
</label>
</li>
</ol>
What I am trying to do is highlight/check the answers that the user chose using the json result. I can't edit the json, as the backend was built for something else and I am trying to repurpose it for this quiz. Does anyone know of a way to parse through the json and use it to automatically populate the users answers?
here is a jsfiddle: http://jsfiddle.net/mtca9kax/
Thanks,
S
EDIT
http://jsfiddle.net/mtca9kax/2/
I've updated my fiddle to include a more accurate json response. There are also questions that have multiple answers (see Q2... lots of T/F). I've got it working, but don't know how to loop over the data.
This is how I would do it:
You have to loop into your json response, and use the values to select the proper answer.
$.each(results.form, function (ind, val) {
$.each(val, function (inde, value) {
$.each(value, function (index, radio) {
//console.log(radio);
$('input[name="'+ inde +'"][value="'+ radio +'"]').prop("checked", true);
});
});
});
FIDDLE.
You should do loop upon JSON object and map key M1_Q1PRE (for example) on the element with same name.
If you don't like clear javascript use jQuery library or same
(jQuery.each -- for loop, jQuery(element).val() -- for set value to the element).
You can iterate over the json/js-object and set the checked property for the users answers:
var answers = JSON.parse(your_json);
for(var i in answers) {
var answer = answers[i];
$('ol:eq(+'parseInt(i)+)' input[value="'+answer['M1_Q'+i+'PRE']+'"]').prop('checked', 'checked');
}
As you see, the json format has room for optimization for this purpose ;-)
Oh, there are actually the answers ids as key and values inside the M1_Q... objects - that needs to be solved to make the answer above work... the general idea should be visible, however.
(Better change the json to a more appropriate format.)
Related
Hey so I'm currently a newbie in Vue so have some mercy :)
I am trying to implement a filter bar, where I want to render the checked-box onto a collection view. So a use case would be, if T-shirts was checked then that should render all T-shirts from a DB.
So currently I'm grabbing all the values of beers from my database and rendering that into my filter box:
<div class="overflow menu-list">
<ul>
<li v-for="brewery in breweryName">
<input type="checkbox" name="beer">{{brewery}}
</li>
</ul>
</div>
Where my Vue instance is defined as so:
var filterVM = new Vue({
el: '#filter-bar',
data : {
breweryName : grabFromBeerDB("brewery"),
beerStyle : grabFromBeerDB("style"),
checkedBrewery : []
},
firebase : {
beerList: beerDatabaseRef
}, ...
My only question here is how would I reactively grab the values of the boxes that are checked?
Thanks for the help
Just use v-model
<input type="checkbox" name="beer" value="A" v-model="checkedBrewery">
<input type="checkbox" name="beer" value="B" v-model="checkedBrewery">
<input type="checkbox" name="beer" value="C" v-model="checkedBrewery">
docs: https://v2.vuejs.org/v2/guide/forms.html#Checkbox
<li v-for="brewery in breweryName">
<input type="checkbox" name="beer" :value="brewery" v-model="checkedBrewery">
{{brewery}}
</li>
The value of input is required, and you must make sure each value is different with others.
I would like to check boxes via javascript.
The thing is I have a task to check more then 300 checkboxes whith specific names.
I can check one box, or check all boxes... but how to check specific boxes?
Here is an example:
<li id="s1" class="city-select">
<input name="rid" id="r1" value="1" type="checkbox">
<label for="r1" id="l1">Paris</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r2" value="2" type="checkbox">
<label for="r2" id="l2">Plovdiv</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
I would like to tick only "Berlin" and "Paris" - here is what I'm using to tick all:
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
And here is what am I trying to type:
$("lable:contains('paris, berlin')").prev().find('input').addAttr("checked");
You have wrong selector to target checkboxes. You need to use:
$("label:contains(Paris),label:contains(Berlin)").prev().prop("checked",true);
Working Demo
Update:
var cities = ["Paris","Berlin"];
$("label:contains('" + cities.join("'),label:contains('") + "')").prev().prop("checked",true);
Working Fiddle for update
It looks like your use of prev should be parent or closest.
So you take the current label, go up to the container, then down to the checkbox.
If you use prev then you restrict how much you can change the html (eg if you add a div wrapper around the label in the future, you'll have to change all your code).
given:
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
then use
$("label:contains(Paris),label:contains(Berlin)")
.closest("li")
.find(":checkbox")
.prop("checked",true);
More info at the API documentation: https://api.jquery.com/closest/
How to use this for 300 cities?
This depends on how they are stored. If it's a comma separated list (Paris,Berlin) then split into an array first, if it's json, then convert to an array first...(see the pattern?)
var citiesList = "Paris,Berlin".split(",");
$(citiesList).each(function() {
$("label:contains(" + this + ")")
.closest("li")
.find(":checkbox")
.prop("checked",true);
});
This section of code uses jQuery to hide/show form fields. When they are hidden the values of those fields are set to empty. This is easy for an input field with its unique ID. I run into trouble with checkboxes. The code below works for three checkboxes. But I have to use this same technique for a set of 26 checkboxes. How can I do this more efficiently?
$(".transfer").click(function(){
if ($('input[name=transfer_position]:checked').val() == "yes" ) {
//Slide Down Effect
$(".transfer_details").slideDown("slow");
document.getElementById('transfer_interest').focus();
} else {
//Slide Up Effect
$(".transfer_details").slideUp("slow");
document.getElementById('transfer_interest').value = "";
document.getElementById('select_positions_0').checked = false;
document.getElementById('select_positions_1').checked = false;
document.getElementById('select_positions_2').checked = false;
}
});
<li>
<label>
<input type="radio" name="transfer_position" class="transfer" value="yes" id="transfer_position_0" />
Yes</label>
<label>
<input type="radio" name="transfer_position" class="transfer" value="no" id="transfer_position_1" />
No</label>
</li>
<li class="transfer_details">
<label for="transfer_interest">Why are you interested in transferring to your selected SL positions and what would you bring to that position(s) and team(s)?</label>
<textarea name="transfer_interest" id="transfer_interest" cols="80" rows="6"> </textarea>
</li>
<li class="transfer_details">
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Resident Advisor" id="select_positions_0" />
Resident Advisor</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Programming Assistant" id="select_positions_1" />
Programming Assistant</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Social Justice Advocate " id="select_positions_2" />
Social Justice Advocate </label>
</li>
Use classes, since many elements can share a class. So you simply uncheck all checkboxes with a certain class:
$('.select_positions').attr('checked', false);
Use the amazing power of jquery's selectors, of course!
$('li.transfer_details input[type=checkbox]').prop("checked", false);
descendant selector - http://api.jquery.com/descendant-selector/
setting the checked attribute -
http://api.jquery.com/prop/
One approach would be to use the child selector in conjunction with the checkbox selector, and iterating using the each function in jQuery to accomplish what you're looking for.
Keep in mind this is untested, so its probably going to raise errors and I trust you to fix that.
Beneath your slide up effect, you'd want something like the following:
$('.transfer_details > input:checkbox').each(function() {
(this).checked = false;
});
Hope this helps and happy coding!
i want to select an input by his value.
the problem is that i got a 4 radio inputs
and when the user clicks "next" it saves the value of that answer in AnsW array.
and when the user clicks "back" i want the input radio button with the value that i have in my AnsW array to be checked, so the user can know what he has selected and change his answer to something else.
html code:
<ul>
<li class="li0">
<input type="radio" value="ch1" name="choice" id="li0"/>
<label for="li0"></label>
</li>
<li class="li1">
<input type="radio" value="ch2" name="choice" id="li1"/>
<label for="li1"></label>
</li>
<li class="li2">
<input type="radio" value="ch3" name="choice" id="li2"/>
<label for="li2"></label>
</li>
<li class="li3">
<input type="radio" value="ch4" name="choice" id="li3"/>
<label for="li3"></label>
</li>
</ul>
my code is:
function go_back(){
$("#back").bind("click",function(){
qNum--;
showQuestion(qNum);
if(AnsW.length === 0){
calcAnswers--;
}
alert(AnsW[qNum]);
tempAns = AnsW[qNum];//user last answer which is false i need this to make the radio button point to that answer
//alert( $("input[value='tempAns']"));
$("input").val(tempAns).attr('checked', true);
alert(tempAns);
//alert(tempAns);
AnsW.splice(-1,1);//delete the false answer from the array i need this to make sure that the answer is deleted and there wont be overload of wrong answers
//alert(deleteAns);
if(qNum === 0){
$("#back").css({"visibility":"hidden"})
}
});
}
jQuery selectors allow you to find elements based on their attributes, an exact match example:
$("element.class[attribute=value]")
Check the value attribute in the selector
$("input[value="+tempAns+"]").prop('checked', true)
I'm trying to grab the value of a hidden field that resides above each group of LI's with javascript, I cannot use jQuery because of an unreasonable client's concerns (believe me, I've tried, they just don't want to "risk" adding a library)... anyway...
The list would look something like this:
<input id="hidden1" type="hidden" value="5" class="includeds">
<h3>header</h3>
<ul class="groups">
<li><input id="li1" type="checkbox" value="1" onclick="value()"></li>
<li><input id="li2" type="checkbox" value="2" onclick="value()"></li>
<li><input id="li3" type="checkbox" value="3" onclick="value()"></li>
</ul>
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value()"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value()"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value()"></li>
</ul>
So if I click on checkbox li1, I want to retrieve the value "5" from the hidden field above it.
If I click li5, I want to get the value of "2" from the first hidden field above it, etc, etc.
in a previous SO question some amazing people helped me do this with jQuery:
if($(this).closest('ul').prevAll('.includeds:first').val() !== '0') {
// logic here
}
but when presented to the client, I ran into the aforementioned complaints. So now I need to do the same thing with javascript vanilla. I appreciate any help or pointers you guys could provide. I apologize for asking the same question twice, between jquery and javascript.
Uhm, the jQuery code I'd use would be:
$(this).parent().prev().prev().val()
With that in mind, all you have to do is rewrite the code to correct plain javascript entities.
The result would be something like:
function getParent(node){
return node.parentNode;
}
function getPrev(node){
do { // loop to find the previous node that is an element
node = node.previousSibling;
}while(node && node.nodeType != 1);
return node;
}
getPrev(getPrev(getParent(this))));
If you can't use jQuery then complex queries like the on you mentioned become much more difficult. In liue of jQuery it's easiest to reference elements by their ID tag or by a class filter (depending on the scenario).
Here i would say the best bet is to hard code the given input ID into the onclick function.
HTML
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value('hidden2')"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value('hidden2')"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value('hidden2')"></li>
</ul>
JavaScript
function value(id) {
var elem = document.getElementByID(id);
...
}