I'm trying to make a quiz powered by jQuery (and maybe JSON), with the values stored in a database. It works fine so far, but I'd like to hide the radio buttons (CSS: display: none) and make each question look like a button (much easier to select than a tiny radio button).
However, when I do this, the following JavaScript doesn't work, and the quiz isn't scored.
var imgpath = "/images/sections/test/";
var jsonpath = "/2b/inc/pages/quiz-php/json/";
var jsonfile = "key";
$(document).ready(function(){
//Make sure radio buttons are not disabled or checked (helpful when refreshing)
$("input[type='radio']").attr("disabled", false);
$("input[type='radio']").attr("checked", false);
$(".submit").click(function(e){
e.preventDefault();
//Check the quiz results
checkQuiz();
});
//Build the json filename
jsonfile = $("#quiz").attr("rel")+".php";
});
//Load json file
function getData(update){
$.getJSON(jsonpath+jsonfile, function(json){
//Execute the callback
update(json);
}).error(function(){alert("error");});
}
function checkQuiz(){
$(".submit").remove();
getData(function(data){
var ans = data.key;
var result = {};
$(".Question").each(function(){
//Get the question id
var _q = $(this).attr("id");
//Get the selected answer class
var _a = $("#"+_q+" input:checked").closest("li").attr("class");
//Add the values to the result object
result[_q] = _a;
//Compare the selected answer with the correct answer
if(ans[_q]==_a){
$(this).addClass("correct");
}else{
$(this).addClass("wrong");
}
});
//Build the feedback
var fdbck = "You got "+$(".correct").length+" out of "+$(".Question").length+" correct. "
if($(".correct").length==0){
fdbck += "Better luck next time.";
}else if($(".correct").length>$(".Question").length/2){
fdbck += "Good job!";
}else{
fdbck += "Not bad.";
}
$(".feedback").text(fdbck);
$(".feedback").show();
});
}
So I wondered if there's some way to record scores besides a radio button. I created a JSFiddle # http://jsfiddle.net/9j7fz99w/6/ to illustrate how I'm using jQuery and CSS to style correct and incorrect answers. Is there a way to modify the code above to similarly recognize correct questions based on their "selection," rather than a radio button?
Just a small example using a JS questions Array with Objects
var $quizEl = $("#quizEl");
var $submit = $("#submit");
var quiz = [
{ // obj
"Q" : "What color is the Sun?",
"A" : ["Red", "Black", "Yellow"],
"C" : 2
},{
"Q" : "What color is an Elephant?",
"A" : ["Gray", "Blue", "Yellow"],
"C" : 0 // zero indexed!
},{
"Q" : "What color is the Sea?",
"A" : ["Fuchsia", "Blue", "Gold"],
"C" : 1
}
];
var qNum = quiz.length;
// FUNCTION THAT CREATES AND APPENDS AN `UL` TO `DIV #quizEl`
function generateQuestion( obj, idx ) {
var html = "<h2>"+ obj.Q +"</h2><ul>";
for (var i=0; i<obj.A.length; i++) {
html += "<li>"+
"<label>"+
"<input type='radio' name='"+ idx +"' value='"+i+"'>"+
obj.A[i] +"</label>"+
"</li>";
}
$quizEl.append( html+"</ul>" );
}
// GENERATE ALL QUESTIONS:
for(var i=0; i<qNum; i++) {
generateQuestion( quiz[i], i ); // quiz[i] is the {QAC} object
}
$quizEl.on("change", ":radio", function(){ // Record User choice (U property)
quiz[this.name].U = this.value; // set 0,1,2 to the new U property {QACU}
});
$submit.on("click", function(e){
e.preventDefault();
console.log( quiz ); // To test how it looks
// Check if user answered them all:
for(var i=0; i<qNum;i++){
if(!quiz[i].hasOwnProperty("U")){ // User did not answered if "U" property doesn't exists
return alert("Please,\nanswer the question "+ (i+1) +":\n"+ quiz[i].Q );
}else{ // Add classes...
$("ul").eq(i).find(":checked").closest("li")
.addClass( +quiz[i].U === quiz[i].C ? "correct":"wrong");
}
}
// Finally colour them!
$(".correct").css({background:"green"});
$(".wrong").css({background:"red"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quizEl"></div>
<input id="submit" type="submit">
Related
I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}
I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}
I need to split an array into an JSON array which should be following pattern.
{{"url":url, "north":True "side":True}, {"url":url, "north":False, "side":True}}
I get the url parameter with this code. As you can see here, this code displays 3 checkboxes where you can select if the picture is north, on the side or if you want to select it.
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
xmlDoc = xmlHttp.responseXML;
pictureTemp = [document.getElementById("imgfilename")];
$('.login-form').append('<button onclick="sendAuswahl()">Send</button><br>');
for (var i = 0; i < xmlDoc.getElementsByTagName("imgfilename").length; i++) {
pictureTemp[i] = xmlDoc.getElementsByTagName("imgfilename")[i].childNodes[0].nodeValue;
$('.login-form').append('<input type="checkbox" name="north" value="North"><input type="checkbox" name="orientation" value="Side"><input type="checkbox" name="url" value='+ pictureTemp[i]+'><img src='+ pictureTemp[i]+' width="50%"></br>');
};
}
To get all ticked checkboxes, I use this code:
var arrayUrl = $("input[name='url']:checked").map(function(){
return this.value;
}).get()
var arrayNorth = $("input[name='north']:checked").map(function(){
return "True";
}).get()
var arrayOrientation = $("input[name='orientation']:checked").map(function(){
return "True";
}).get()
To convert the selection to a JavaScript object and to get the pattern which I described above, I use this:
var picture = {
"url" : arrayUrl,
"North" : arrayNorth,
"Side" : arrayOrientation
};
But when I alert the value of a selected image I get this:
{"url":http://www.example.com, "north":True "side":True}
And when I select 2 images I get this:
{"url":http://www.example.com, http://www.example2.com, "north":True "side":False}
Instead of this:
{{"url":http://www.example.com, "north":True "side":False}, {"url":http://www.example2.com, "north":False, "side":True}}
So my question is now: How can I adept the values in the pattern which I've described above?
var picture = [];
$.each(arrayUrl, function(index,val) {
val = {
"url" : val,
"North" : arrayNorth[index],
"Side" : arrayOrientation[index]
};
picture.push(val);
});
var picture = [];
$(arrayUrl).each(function(index) {
picture.push({
"url": arrayUrl[index],
"North": arrayNorth[index],
"Side": arrayOrientation[index]
});
});
I'm new to JS. I'm trying to delete the parent node with all the children by clicking a button. But the console tells me that undefined is not a function. What am I missing?
Fiddle:
http://jsfiddle.net/vy0d8bqt/
HTML:
<button type="button" id="output">Get contacts</button>
<button type="button" id="clear_contacts">clear contact</button>
<div id="output_here"></div>
JS:
// contact book, getting data from JSON and outputting via a button
// define a JSON structure
var contacts = {
"friends" :
[
{
"name" : "name1",
"surname" : "surname1"
},
{
"name" : "name2",
"surname" : "surname2"
}
]
};
//get button ID and id of div where content will be shown
var get_contacts_btn = document.getElementById("output");
var output = document.getElementById("output_here");
var clear = document.getElementById("clear_contacts");
var i;
// get length of JSON
var contacts_length = contacts.friends.length;
get_contacts_btn.addEventListener('click', function(){
//console.log("clicked");
for(i = 0; i < contacts_length; i++){
var data = contacts.friends[i];
var name = data.name;
var surname = data.surname;
output.style.display = 'block';
output.innerHTML += "<p> name: " + name + "| surname: " + surname + "</p>";
}
});
//get Children of output div to remove them on clear button
//get output to clear
output_to_clear = document.getElementById("output_here");
clear.addEventListener('click', function(){
output_to_clear.removeNode(true);
});
You should use remove() instead of removeNode()
http://jsfiddle.net/vy0d8bqt/1/
However, this also removes the output_to_clear node itself. You can use output_to_clear.innerHTML = '' if you like to just delete all content of the node, but not removing the node itself (so you can click 'get contacts' button again after clearing it)
http://jsfiddle.net/vy0d8bqt/3/
You want this for broad support:
output_to_clear.parentNode.removeChild(output_to_clear);
Or this in modern browsers only:
output_to_clear.remove();
But either way, make sure you don't try to remove it after it has already been removed. Since you're caching the reference, that could be an issue, so this may be safer:
if (output_to_clear.parentNode != null) {
output_to_clear.remove();
}
If you were hoping to empty its content, then do this:
while (output_to_clear.firstChild) {
output_to_clear.removeChild(output_to_clear.firstChild);
}
I think using jQuery's $.remove() is probably the best choice here. If you can't or don't want to use jQuery, The Mozilla docs for Node provides a function to remove all child nodes.
Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
};
Which you would use like:
output_to_clear.removeAll();
For a one-off given the example provided:
while (output_to_clear.firstChild) { output_to_clear.removeChild(output_to_clear.firstChild); }
I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..