I have a json file which contains questions and answers like this.
{
"Questions": [
{ "Q": "I enjoy playing video games" },
{ "Q": "I enjoy reading" },
{ "Q": "I enjoy watching tv" }
],
"Answers": [
{
"a": "Strongly Agree",
"b": "Agree",
"c": "Neutral",
"d": "Disagree",
"e": "Strongly Disagree"
}
]
}
The answers are always the same for each question. I am trying to do a loop in javascript to display each questiona the answers under it, something like this
1.I enjoy video games
RadioButton:Strongly agree RadioButton:Agree etc...
2. I enjoy reading
RadioButton:Strongly agree RadioButton:Agree etc...
right now i have this, but it doesn't really work
$.getJSON("questions.json",function(data)
{
$.each(data, function(i,data)
{
var div = document.createElement("div");
div.setAttribute("id", i);
document.createElement("div").setAttribute("id", i);
var div_data = "<div class='questions'><h2>" + data.Questions.Q +"</h2><br />"+
"<input type='radio' name='q" + i + "' id='q" + i + 1+"' value='"+data.Answers.a+"'/>" +
"<label for='q" + i + 1+"'>" + data.Answers.a + "</label>"+
"<input type='radio' name='q" + i + "' id='q" + i + 2+"' value='"+data.Answers.b+"'/>" +
"<label for='q" + i + 2+"'>" + data.Answers.b + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + 3+"' value='"+data.Answers.c+"'/>" +
"<label for='q" + i + 3+"'>" + data.Answers.c + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + 4+"' value='"+data.Answers.d+"'/>" +
"<label for='q" + i + 4+"'>" + data.Answers.d + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + 5+"' value='"+data.Answers.e+"'/>" +
"<label for='q" + i + 5+"'>" + data.Answers.e + "</label>"
+"</div>" ;
document.getElementById("box").appendChild(div);
div.innerHTML = div_data;
});
});
You have to loop through data.Questions. See the code below. I have also optimized your code, so that the HTML is appended at once, rather than separately for each element.
Another note: You should change the i + 1, 1 + 2, 1 + 3, etc part to something more appropriate. Currently, it's just added, because it's inside a string context. Even if you add parentheses, the logic is still flawed: For i=1, i+2 = 3. For i=2, i+1 is also 3.
I have replaced i + 1 + "' with i + "_1', to give you an idea of the right approach.
$.getJSON("questions.json",function(data)
{
var html = "";
$.each(data.Questions, function(i, question)
{
html += "<div id=" + i + ">" +
"<div class='questions'><h2>" + question.Q +"</h2><br />"+
"<input type='radio' name='q" + i + "' id='q" + i + "_1' value='"+data.Answers.a+"'/>" +
"<label for='q" + (i + "_1'>" + data.Answers.a + "</label>"+
"<input type='radio' name='q" + i + "' id='q" + i + "_2' value='"+data.Answers.b+"'/>" +
"<label for='q" + i + "_2'>" + data.Answers.b + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + "_3' value='"+data.Answers.c+"'/>" +
"<label for='q" + i + "_3'>" + data.Answers.c + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + "_4' value='"+data.Answers.d+"'/>" +
"<label for='q" + i + "_4'>" + data.Answers.d + "</label>" +
"<input type='radio' name='q" + i + "' id='q" + i + "_5' value='"+data.Answers.e+"'/>" +
"<label for='q" + i + "_5'>" + data.Answers.e + "</label>"
+ "</div></div>" ;
});
$("#box").append(html);
});
You aren't accessing the JSON properly. data.Questions.Q and data.Answers.a is not correct.
Both data.Questions and data.Answers are arrays. You would have to loop through those arrays and access them like data.Questions[i].Q.
Or change your JSON to match how you want the code to be able to iterate them. You can fix one or the other, but the two must match. It looks to me like you want to fix the code for the questions and fix the JSON for the answers, but that's a design decision that you can make.
Related
I was wondering if someone could shed some light on my code and why it may not be working. I am running nodejs 6+ with an electron wrapper.
dependencies for the sqlite are "sqlite3": "^3.1.8
I am managing to list and display the data in rows without issue but on the insert function or search function it is falling over. I must be doing something wrong.
function insertNewVeh() {
db.all("INSERT INTO vehicles VALUES ('" +
document.getElementById('regNo').value + "','" +
document.getElementById('firstName').value + "','" +
document.getElementById('lastName').value +
"')", function(err, rows) {
console.log.msg;
})
}
insertNewVeh();
function srchReg() {
var regNo = document.getElementById("regNo").value
db.all("SELECT ALL FROM VEHICLES WHERE regNo = " + regNo + ""), function(err, rows) {
var reg = document.getElementById("newVehicle").value
rows.forEach(function (row) {
console.log.msg;
document.getElementById('sReg').innerHTML =
"<div>Total</div>"
})
};
};
srchReg();
and the functions
function srchDiv() {
document.getElementById('rSrch').innerHTML =
"<form>" +
"<input type=\"search\" id=\regNo\" placeholder=\"What are you looking for?\">" +
"<button id=\"subSrch\">Search</button>" +
"</form>";
document.getElementById('subSrch').addEventListener("click", function (e) {
srchReg();
});
}
srchDiv();
window.onload = function addVeh() {
document.getElementById('nVeh1').innerHTML =
"<form>" +
"<div class=\"row\">" +
"<label for=\"firstName\" id=\"firstName\">First Name</label>" +
"<input id=\"firstName\" name=\"firstName\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"lastName\" id=\"lastName\">Last Name</label>" +
"<input id=\"lastName\" name=\"lastName\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"address1\" id=\"address1\">Address 1</label>" +
"<input id=\"address1\" name=\"address1\" type=\"text\" />" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"address2\" id=\"address2\">Address 2</label>" +
"<input id=\"address2\" name=\"address2\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"town\" id=\"town\">Town</label>" +
"<input id=\"town\" name=\"town\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"postcode\" id=\"postcode\">Post Code</label>" +
"<input id=\"postcode\" name=\"postcode\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<label for=\"telephone\" id=\"telephone\">Telephone</label>" +
"<input id=\"telephone\" name=\"telephone\" type=\"tel\"/>" +
"</div>";
document.getElementById('nVeh2').innerHTML =
"<div class=\"row\">" +
"<label for=\"regNo\" id=\"regNo\">regNo</label>" +
"<input id=\"regNo\" name=\"regNo\" type=\"text\"/>" +
"</div>" +
"<div class=\"row\">" +
"<button type=\"submit\" value=\"Add\" id=\"addV\"/>Add</button>" +
"</div>" +
"</form>";
document.getElementById('addV').addEventListener("click", function (e) {
insertNewVeh();
});
}
addVeh();
I am relatively sure it's a syntax error somewhere but can't see it as I am still new to javascript. In either function the search doesnt work, nor does it insert anything to the database.
Note the 'return false', since your are submitting a form
function insertNewVeh() {
const self = this
db.serialize(
function () {
let stmnt = db.prepare('INSERT INTO vehicles VALUES (?, ?, ?)')
stmnt.run(document.getElementById('regNo').value, document.getElementById('firstName').value, document.getElementById('lastName').value, function () {
stmnt.finalize(function () {
// Here goes your callback, if you need one
// self.doSomeThing()
})
})
}
)
return false
}
This is a jsfiddle about the problem.
http://jsfiddle.net/BHL3P/1/
var FiltersCount = 0;
var currentMinHeight = 20;
var filterDiv = "" +
"<div style='border: 2px solid #003d4c; margin: 5px'>" +
"<div style='width: 45%' class='input select'>" +
"<label for='ReportFilter" + FiltersCount + "Field'>Select a Filter</label>" +
"<select id='ReportFilter" + FiltersCount + "Field' style='width: 100%' name='data[Report][filter][" + FiltersCount + "][field]'>" +
"<option value='product'>Filter" + FiltersCount + "</option>" +
"</select>" +
"</div>" +
"<div style='width: 45%' class='input text'>" +
"<label for='ReportFilter" + FiltersCount + "Value'>Type a Value</label>" +
"<input type='text' id='ReportFilter" + FiltersCount + "Value' style='width: 100%' name='data[Report][filter][" + FiltersCount + "][value]'>" +
"</div>" +
"</div>";
$(document).ready(function () {
$("#moreFilters").append(filterDiv);
$("#addFilter").click(function () {
FiltersCount = FiltersCount + 1;
$("#moreFilters").append(filterDiv);
});
});
I'm creating a series of filters for a research form. Every field have a progressive number that differentiate the name from the others.
I'm clearly doing something wrong because even if the variable is changed, the created HTML keep using the initial value.
try this. i think because you save earlier on variable on top so it wont change value of filterscount inline on variable filterdiv. im not test it but i think it work.. sorry for my english :P
var FiltersCount = -1;
var currentMinHeight = 20;
$(document).ready(function () {
$("#addFilter").click(function () {
FiltersCount = FiltersCount + 1;
var filterDiv = "" +
"<div style='border: 2px solid #003d4c; margin: 5px'>" +
"<div style='width: 45%' class='input select'>" +
"<label for='ReportFilter" + FiltersCount + "Field'>Select a Filter</label>" +
"<select id='ReportFilter" + FiltersCount + "Field' style='width: 100%' name='data[Report][filter][" + FiltersCount + "][field]'>" +
"<option value='product'>Filter" + FiltersCount + "</option>" +
"</select>" +
"</div>" +
"<div style='width: 45%' class='input text'>" +
"<label for='ReportFilter" + FiltersCount + "Value'>Type a Value</label>" +
"<input type='text' id='ReportFilter" + FiltersCount + "Value' style='width: 100%' name='data[Report][filter][" + FiltersCount + "][value]'>" +
"</div>" +
"</div>";
$("#moreFilters").append(filterDiv);
});
});
I'm using a plugin to rate values: http://www.radioactivethinking.com/rateit/example/example.htm
The following code works if I put directly into the HTML.
<li>
<p><strong>Product</strong>
<br/>
<input type="range" value="0" step="1" id="rateit" data-role="none">
<div class="rateit" id="rateitHover" data-rateit-backingfld="#rateit" data-rateit-resetable="false" data-rateit-ispreset="true"
data-rateit-min="0" data-rateit-max="5">
</div>
</p>
</li>
The code below doesn't work, it retrieves the default <input type="range"> by html.
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div class='rateit' id='" + 'rateIt' + item.id + "' data-rateit-backingfld='" + 'rateIt' + item.id + "' data-rateit-resetable='false' data-rateit-ispreset='true' " +
"data-rateit-min='0' data-rateit-max='5'></div></p></li>";
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
How do I turn this into that plugin? Thanks!
You have a syntax error on your 4th/5th line. Take a look at your "'s you have an extra.
info += "<li id='" + item.id + "'><p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div class='rateit' id='" + 'rateIt' + item.id + "' data-rateit-backingfld='" + 'rateIt' + item.id + "' data-rateit-resetable='false' data-rateit-ispreset='true' " +
"data-rateit-min='0' data-rateit-max='5'></div></p></li>";
Ok, I've found that this is some kind of bug or something. I've tested with another plugins and doesn't work either. I'm now using a better plugin, which is more easier.
https://github.com/wbotelhos/raty
The html is very simple: <div id="score"></div>, although it is necessary to call it on jQuery.
$("#score").raty({
score: function() {
return $(this).attr('data-rating');
}
});
I've tried to adapt it and make all IDs uniques:
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div id=" + 'score' + item.id + "></div></p></li>";
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
But continues not to work. I've tried in vain also:
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div id=" + 'score' + item.id + "></div></p></li>";
$("#score" + item.id).raty({
score: function() {
return $(this).attr('data-rating');
}
});
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
Btw, I'm loading this function before page show..I don't know if that's the problem.
$(document).on("pagebeforeshow", "#main", function() {
$(function(){
get_info();
});
})
I am appending check-boxes in a div by jQuery. Div is scroll when overflow. But I see that when checkbox names are large then div does not horizontally scroll but extra content goes to next line while vertical scroll works fine . below is some code
below is code of div creation
<div id="legendBox" style="overflow:scroll;width:145px;height:300px;"></div>
This code is to add check boxes in DIV
if (legendChecked == "T")
{
legendtest = "<input type='checkbox' class='" + legendClass + "' name='" + legendName + "' style='background-color:" + legendColor + "' value='" + legendName + "' checked onClick=legendChanged(); title='" + legendName + "' />" + legendName;
} else
{
legendtest = "<input type='checkbox' class='" + legendClass + "' name='" + legendName + "' style='background-color:" + legendColor + "' value='" + legendName + "' onClick=legendChanged(); title='" + legendName + "' />" + legendName;
}
$("#legendBox").append(legendtest+"</br>");
Please tell me where is mistake.
Or add display:inline: http://jsfiddle.net/eq3r9/
Edit:
This is a better solution: http://jsfiddle.net/eq3r9/1/
Afternoon,
I would like to increase the number in this code by 1 for each question displayed.
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question 1</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
With this it would show, question 1, question 2, and so on...
How would i go about doing this in jQuery please?
Update Victor provided what i needed, thanks all for your help. Updated code below.
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);
Declare a variable outside your loop and incremenet it inside your loop and use that in the markup.
var questionNumber=0;
$.each(someJsonData, function (index, res) {
{
questionNumber++;
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question "+questionNumber+"</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
}
Declare a var called questionNumber and increment it at each call
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);