Jquery match for json data - javascript

I'm trying to pull out data from my json using match() in my search function. Here's what I want to do using the string inputted in the textbox. It would then pull out data from my json array as long as there is a match. Here's what I have so far:
var data = [{
"RM_Name": "Russ Martin",
"Division": "East",
"RM_Phone": "(603) 491-1259",
"RC_Name": "Jacob Sucoff",
"RC_Phone": "(800) 247-4154 x3403",
"States_Covered": "MT,VT, NH, ME (all firms)",
"Latitude": 46.6797995,
"Longitude": -110.044783,
"Coordinates": "46.6797995,-110.044783"
}, {
"RM_Name": "Carey Fortnam",
"Division": "East",
"RM_Phone": "(585)-259-7394",
"RC_Name": "Matt Wrzesniewsky",
"RC_Phone": "(800) 247-4154 x3088",
"States_Covered": "NY- Upstate ex Rockland County (BD, FP)",
"Latitude": 40.7056308,
"Longitude": -73.9780035,
"Coordinates": "40.7056308,-73.9780035"
}];
$.each(data, function(i, item) {
var rm_name = item.RM_Name,division = item.Division,rm_phone = item.RM_Phone,rc_name = item.RC_Name,rc_phone = item.RC_Phone,states = item.States_Covered;
var dataset='<tr class="'+rm_name+' '+rc_name+'"><td>'+rm_name+'</td><td>'+division+'</td><td>'+rm_phone+'</td><td>'+rc_name+'</td><td>'+rc_phone+'</td><td>'+states+'</td></tr>';
$('.rm-data').append(dataset);
});
$('#search').on('keypress', function (e) {
if(e.which == 13) {
search();
}
}).on('change', function (e) {
search();
});
function search() {
var query = $('#search').val();
// empty?
if(query === "")
{
$('.rm-data tr').show();
return;
}
$('.rm-data tr').hide();
$('.error-msg').hide();
if ($('.rm-data tr').hasClass(query)) {
$('.rm-data tr:contains(' + query + ')').fadeIn('slow', function () {
$('.rm-data tr:contains(' + query + ')').slideDown().show();
});
}
else {
//JSON Match Finder
$.getJSON(data, function (data) {
$.each(data, function (i, item) {
var test= item.RM_Name+' '+item.RC_Name;
var regex = new RegExp(query);
var test2 = test.match(regex);
console.dir(test2);
});
});
var error = '<div class="error-msg">Contact Not Found</div>';
$('.rm-table-search').append(error);
if ($('.error-msg').length == 0) {
$('.rm-table').append(error);
}
else {
$('.rm-table').append('');
}
}
}
I am able to find matches using this code but I cannot pull the data out. Is there anyway I can do this? Fiddle here.
Just sharing my output so far via console.log()
["Ru", index: 0, input: "Russ MartinJacob Sucoff", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
6
null ab-rm.js:80
["Ru", index: 18, input: "Kevin GangMichael Rus", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
12
null ab-rm.js:80
["Ru", index: 0, input: "Russ CorbyNatasha Fomenko", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
8
null ab-rm.js:80
["Ru", index: 6, input: "Laura RupsisKenny Meyer", $family: function, $constructor: function, pop: function…]

I figured it out based on balexandre's idea:
$.each(data, function (i, item) {
var rm_name = item.RM_Name,
division = item.Division,
rm_phone = item.RM_Phone,
rc_name = item.RC_Name,
rc_phone = item.RC_Phone,
states = item.States_Covered;
var dataset = '<tr class="' + rm_name + ' ' + rc_name + '"><td>' + rm_name + '</td><td>' + division + '</td><td>' + rm_phone + '</td><td>' + rc_name + '</td><td>' + rc_phone + '</td><td>' + states + '</td></tr>';
$('.rm-data').append(dataset);
});
function search() {
var query = $('#search').val();
$('.rm-data tr').hide();
$('.error-msg').hide();
if ($('.rm-data tr').hasClass(query)) {
$('.rm-data tr:contains(' + query + ')').fadeIn('slow', function () {
$('.rm-data tr:contains(' + query + ')').slideDown().show();
});
} else {
var combined_array = [];
$.each(data, function (i, item) {
combined_array.push(item.RM_Name);
combined_array.push(item.RC_Name);
});
$.each(combined_array, function (i, item) {
var contents = item;
var array_check = item.indexOf(query) >= 0;
var matches = ''+contents+'';
$('#search-helper-container').append(matches);
$('.false').remove();
$('#search-helper-container').css('display', 'block');
});
var error = '<div class="error-msg">Contact Not Found</div>';
$('.rm-table-search').append(error);
if ($('.error-msg').length == 0) {
$('.rm-table').append(error);
} else {
$('.rm-table').append('');
}
}
}
$('#search-button').on('click', function () {
search();
});
$('#search').on('focus', function () {
$('#search').val('');
$('.true').remove();
$('#search-helper-container').css('display', 'none');
});
$('#search-helper-container').on('click', 'a.search-match', function (e) {
e.preventDefault();
var inputVal = $(this).text();
$('#search').val(inputVal);
});
And a working Fiddle here.

Related

How can I compare data from two links with Ajax?

I want to compare and print genre_ids in the first link and id in the other link.
Sample:
genre_ids: [
18,
878,
]
{
id: 18,
name: "Drama",
},
{
id: 878,
name: "Science Fiction",
}
Result: Drama, Science Fiction
$(document).ready(function () {
var url = "http://api.themoviedb.org/3/discover/movie?api_key=7196f61181cb7f5b0a28020cd3f603fb&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&item_count=14";
var categories = "https://api.themoviedb.org/3/genre/movie/list?api_key=7196f61181cb7f5b0a28020cd3f603fb&language=en-EN";
$.ajax({
url: url,
method: 'GET',
success: function (data) {
$.ajax({
url: categories,
method: 'GET',
success: function (cat) {
$('#Movies').html(ListMovies(data, cat));
}
});
}
});
function ListMovies(data, cat) {
var card = "";
var cats = "";
for (var i = 0; i < 12; i++) {
card += "<div class='col-sm-3'><div class='card'><img src='https://image.tmdb.org/t/p/w1280" + data.results[i].backdrop_path + "' height='250px' class='card-img-top'><div class='card-body'><h5 class='card-title'>" + data.results[i].original_title + " <span>" + data.results[i].vote_average + "</span></h5><p class='card-text'>" + result should be here + "</p></div></div></div>";
}
return card;
}
});
What about this:
function ListMovies(data, cat) {
var card = "";
for (let i = 0; i < 12; i++) {
let cats = [];
cat.genres.forEach(elem=>{
if(data.results[i].genre_ids.includes(elem.id)) cats.push(elem.name)
})
card += "<div class='col-sm-3'><div class='card'><img src='https://image.tmdb.org/t/p/w1280" + data.results[i].backdrop_path + "' height='250px' class='card-img-top'><div class='card-body'><h5 class='card-title'>" + data.results[i].original_title + " <span>" + data.results[i].vote_average + "</span></h5><p class='card-text'>" + cats.join(", ") + "</p></div></div></div>";
}
return card;
}

Optimize list selected

I have gallery into my project, when page loads it charge all upload images and categories like these:
As you can see, It suit images depending of selected categories. The problem is the page going to slow because it loads all images... How can I do to optimize these process? I think some like delete All categorie, but I don´t know how to do my query to start for example with office categorie filter
There is my code:
function GalleryCatPopulate(url, listname, target) {
var eng = false;
if ((window.location.href.indexOf("lang=en") > 0)) {
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items? $select=Title,English",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryCat(data, target, eng);
},
error: function (data) {
failureGalleryCat(data, target);
}
});
}
function completeGalleryCat(data, target, eng) {
var items = data.d.results;
var prefix = "";
var sufix = "<div class='clear'></div>";
if (eng)
prefix = "<div class='filter selected' data-category='cat-all'>All</div>";
else
prefix = "<div class='filter selected' data-category='cat-all'>Todas</div>";
var menu = "";
var cat = "";
var title = "Transporte de Materiales";
console.log(title.replace(/\s/g, "_").replace(/[^\w\s]/gi, ''));
for (var item in items) {
if (eng)
cat = items[item].English;
else
cat = items[item].Title;
menu += "<div class='filter' data-category='" + cat.replace(/\s/g, "_").replace(/[^\w\s]/gi, '') +"'>"+ cat +"</div>";
}
$(target).html(prefix + menu + sufix);
}
function failureGalleryCat(data, target) {
$(target).text("There is something bad wit load images, please check console");
}
function GalleryContentPopulate(url, listname, target) {
var eng = false;
var queryGallery = "$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title";
if ((window.location.href.indexOf("lang=en") > 0)) {
queryGallery = "$select=TitleEnglish,DescriptionEnglish,Enlace,EncodedAbsUrl,Categoria/English&$expand=Categoria/English";
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$top=1000&" + queryGallery,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryContent(data, target, eng);
},
error: function (data) {
failureGalleryContent(data, target);
}
});
}
function completeGalleryContent(data, target, eng) {
var items = data.d.results;
console.log(items);
var menu = "";
var cat = "";
for (var item in items) {
if(items[item].DescriptionEnglish==null)
items[item].DescriptionEnglish="";
if(items[item].Description==null)
items[item].Description="";
if(items[item].Categoria.results!= null && items[item].Categoria.results!= undefined && items[item].Categoria.results.length > 0){
cat =setCategories(eng,items[item].Categoria.results);
}
if (eng){
menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div> </div>";
}else{
menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
}
}
$(target).html(menu);
var api = $(target).megafoliopro(
{
filterChangeAnimation: "pagebottom", // fade, rotate, scale, rotatescale, pagetop, pagebottom,pagemiddle
filterChangeSpeed: 400, // Speed of Transition
filterChangeRotate: 99, // If you ue scalerotate or rotate you can set the rotation (99 = random !!)
filterChangeScale: 0.6, // Scale Animation Endparameter
delay: 20,
defaultWidth: 980,
paddingHorizontal: 10,
paddingVertical: 10,
layoutarray: [9, 11, 5, 3, 7, 12, 4, 6, 13] // Defines the Layout Types which can be used in the Gallery. 2-9 or "random". You can define more than one, like {5,2,6,4} where the first items will be orderd in layout 5, the next comming items in layout 2, the next comming items in layout 6 etc... You can use also simple {9} then all item ordered in Layout 9 type.
});
//console.log("entra");
// FANCY BOX ( LIVE BOX) WITH MEDIA SUPPORT
jQuery(".fancybox").fancybox();
//console.log("sale");
// THE FILTER FUNCTION
$('.filter').click(function () {
$('.filter').each(function () { jQuery(this).removeClass("selected") });
api.megafilter(jQuery(this).data('category'));
$(this).addClass("selected");
});
var categorySelected = getParameterByName("Category");
$("div[data-category='"+categorySelected +"']").click();
}
function failureGalleryContent(data, target) {
console.log(data);
$(target).text("Error loading parallax. Please check console for more info");
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setCategories(boolLang, objResult){
var cat ="";
for(var item in objResult){
if(boolLang)
cat += replaceAll(" ", "_",objResult[item].English.replace(/[^\w\s]/gi, '')) + ' ';
else
cat += replaceAll(" ", "_",objResult[item].Title.replace(/[^\w\s]/gi, '')) + ' ';
}
return cat;
}
function replaceAll( find, replace,string) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Thankyou in advance!

Use jQuery to draw table

Currently, I am trying to draw a table using jQuery but its not working. This is the current js code. I tried using append but it didnt work for the table. Can someone help me on this. Thank you.
(function(){
var location = new Array();
var query = '%23CM0655';
var url = "search.php";
$.post(url, {query:query}, function(tweets){
console.log(tweets);
$("#tweetResult").html("");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for(var i=0; i<tweets.statuses.length; i++){
var img = $("<img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/>");
$("#tweetResult").append(img);
$("#tweetResult").append('<br/>');
$("#tweetResult").append(tweets.statuses[i].user.screen_name);
$("#tweetResult").append(tweets.statuses[i].text + "<br/>");
geoEnabled = tweets.statuses[i].user.geo_enabled;
if(geoEnabled){
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if(placeName != null){
$("#tweetResult").append(placeName + ", ");
$("#tweetResult").append(countryName + "<br/>");
}
$("#tweetResult").append("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", ");
$("#tweetResult").append(tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>");
$("#tweetResult").append(tweets.statuses[i].created_at);
}
$("#tweetResult").append("<br/><br/>");
}
});
setTimeout(arguments.callee, 10000);
})();
Currently this is the output which i am getting after using the append method to create the table
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
I replicated the issue with some sample data (didn't use every property). But this'll show you how it's done.
Just run the snippet below or check this fiddle out
var tweets = {
statuses: [{
place: {
name: "Oostend",
country: "Belgium"
},
user: {
profile_image_url: "https://jsfiddle.net/img/logo.png",
screen_name: "John Doe",
geo_enabled: true
},
text: "Hello world!",
created_at: "April 7th 2016"
}, {
place: {
name: "Veurne",
country: "Belgium"
},
user: {
profile_image_url: "https://jsfiddle.net/img/logo.png",
screen_name: "Jane Doe",
geo_enabled: false
},
text: "Geo is disabled for me",
created_at: "April 6th 2016"
}]
}
$("#tweetResult").html("");
var table = $("<table></table>");
var thead = $("<thead></thead>");
thead.append($("<th></th>").html("Some header"));
var tbody = $("<tbody></tbody>");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for (var i = 0; i < tweets.statuses.length; i++) {
var row = $("<tr></tr>");
var img = $("<td><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/><br/></td>");
row.append(img);
row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].text + "<br/>"));
geoEnabled = tweets.statuses[i].user.geo_enabled;
if (geoEnabled) {
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if (placeName != null) {
row.append($("<td></td>").html(placeName + ", " + countryName));
}
//row.append($("<td></td>").html("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", " + tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>"));
row.append($("<td></td>").html(tweets.statuses[i].created_at));
}
tbody.append(row);
}
table.append(thead).append(tbody);
$("#tweetResult").append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tweetResult">
</div>
EDIT
I edited the code to your current situation, where as a <table></table> element is created from scratch.

How not to re-write all of those values all over the Function?

As you can see I have this function:
var review = function() {
$('a[name=review_button]').live("click", function (e) {
e.preventDefault();
/*
* #array of reservations
* #all of the fields
*/
var $tr_options = '';
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
var checkbox = $('.multi-transaction:checked').map(function () {
return this.value
}).get();
var options = troptions(reservations, amount, currency_name, currency_value, actual_amount, actual_remaining, funds_arrival_date, paid_to);
$.each(options, function (k, v) {
$tr_options += '<tr>' + '<td>' + k + '</td>' + '<td>' + v + '</td>' + '</tr>';
}); //one line creating trs awesome
var appendto = (
'<table class="table table-striped mb-none">' + '<thead>' +
'<tr>' + '<th>Information</th>' + '<th>Values</th>' + '</tr>' +
'</thead>' +
'<tbody>' + $tr_options + '</tbody>' +
'</table>'
);
$('[name=review-information]').html(appendto);
});
$('button[name=submit-transaction]').live("click", function (e) {
e.preventDefault();
$.ajax({
url: '/transactions/submit',
type: 'POST',
data: {
amount: $('input[name=amount-price]').val(),
currency_value: $('input[name=currency-value]').val(),
currency_name: $('.currency_appendto option:selected').html(),
actual_amount: $('input[name=actual-amount]').val(),
actual_remaining: $('input[name=actual-remaining]').val(),
funds_arrival_date: $('input[name=funds-arrival]').val(),
paid_to: $('.paidto option:selected').html(),
},
success: function (data) {
console.log(data);
}
});
});
}
review();
$(".date-mask").inputmask("d/m/y",{ "placeholder": "dd/mm/yyyy" });
$(".amount-czk").inputmask('integer', { rightAlign: false });
});
Where i have all of those values:
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
And i need to reuse them in multiple areas of the app, however i don't want to re-write those elements all of the time. Writing those values outside the review function returns the .val(); of unidentified. as those values always change .. How can i make a function that will give me back access to all of those values upon call?
Just return them as properties of an Object
function getValues() {
var o = {};
o.reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
o.reservations[i] = $(selected).text();
});
o.amount = $('input[name=amount-price]').val();
o.currency_value = $('input[name=currency-value]').val();
o.currency_name = $('.currency_appendto option:selected').html();
o.actual_amount = $('input[name=actual-amount]').val();
o.actual_remaining = $('input[name=actual-remaining]').val();
o.funds_arrival_date = $('input[name=funds-arrival]').val();
o.paid_to = $('.paidto option:selected').html();
return o;
}
Then access as
var values = getValues();
values.actual_amount; // foo

How to read array from html to js

I declare an array with json data, then when I init the array should be read and display on the div.
But now show nothing, can anyone help me check my code, what mistake I have made. Thanks.
JS Fiddle
HTML
<script>
$(function() {
var array = [];
array[0] = {
"no": "1",
"name": "fruit",
"value": "mango",
"totalvote": "75"
};
array[1] = {
"no": "2",
"name": "fruit",
"value": "apple",
"totalvote": "10"
};
array[2] = {
"no": "3",
"name": "fruit",
"value": "orange",
"totalvote": "5"
};
array[3] = {
"no": "4",
"name": "fruit",
"value": "banana",
"totalvote": "45"
};
PG.init("popup_survey_whitebox_selection", "1", array);
PG.callpopup();
PG.render_1();
});
</script>
JS
var PG = {
divid: "",
multiselection: "",
optionitem: [],
/* type:"", */
init: function (divid, multiselection, optionitem) {
/* PG.type = type;*/
PG.divid = divid;
PG.multiselect = multiselection;
PG.optionitem = optionitem;
},
test: function () {
for (var i = 0; PG.optionitem.length > i; i++) {
alert(PG.optionitem[i].name);
}
},
callpopup: function () {
$("#popup_survey_whitebox_content").hide();
var orig = '', // create var to cache the original text
newText = ''; // create var to cache the new Text with "..."
$("label#popup_survey_label_title").text(function (index, currentText) {
orig = currentText;
newText = currentText.substr(0, 30);
if (currentText.length > 30) newText += "...";
return newText;
});
$("#popup_survey_whitebox").hover(function () {
$('#popup_survey_whitebox_content').stop().animate({
opacity: 1,
height: "toggle"
}, 500, function () {
$("label#popup_survey_label_title").text(orig); // Here put the original text.
}).css('position', 'relative');
}, function () {
$('#popup_survey_whitebox_content').stop().animate({
opacity: 1,
height: "toggle"
}, 500, function () {
$("label#popup_survey_label_title").text(newText); // Here put the new text with "..."
}).css('position', 'relative');
});
$("#popup_survey_end_whitebox").click(function () {
$("#popup_survey_whitebox").remove();
});
},
render_1: function () {
$.each(array, function (i, obj) {
if (PG.multiselect == 1) {
var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='radio' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
"<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
"</div></div>" +
"<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
} else {
var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='checkbox' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
"<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
"</div></div>" +
"<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
}
$("#" + PG.divid).append(selection);
});
var survey_button = "<br><input id='submit_btn' type='button' class='whiteboxbutton whiteboxbutton-small' value='Finish' style='width:100%;'>";
$("#popup_survey_label_title").append("What is your favorite fruit??What is your favorite fruit??");
/*$("#popup_survey_whitebox_title").append();*/
$("#popup_survey_whitebox_inner_title").append("Please select 1 fruit only:");
$('#popup_survey_whitebox_button').append(survey_button);
$('.the_checkbox').on('change', function (evt) {
$('.popup_survey_whitebox_percent').css('display', 'block');
$('.popup_survey_whitebox_progressbar').css('display', 'block');
$(".popup_survey_whitebox_button").show();
if ($(this).siblings(':checked').length >= PG.multiselect) {
this.checked = false;
}
});
},
save: function () {}
}
I console and get this error Uncaught ReferenceError: array is not defined but I must declare on html.
There is other way around as well to solve this error besides closure. Since, you already have optionitem present in PG and you already passed the optionitem to it, you can use it as well inside render_1 method.
Change
$.each(array, function (i, obj) {
to
$.each(PG.optionitem, function (i, obj) {
With that, you need not to define array as a global variable which might conflict with others.
http://jsfiddle.net/5qnhcudp/2/
Your array is in a closure. There is a couple of different things you could do but simply, you can just move your array declaration outside of the closure.
JSFiddle
<script>
var array = [];
$(function() {
...
});
</script>
Found another solution to your problem, your PG object is actually trying to reference the global scope where it doesn't need to. See, your inline script where you declare the array, you are passing that into the PG object.
You have this:
render_1: function () {
$.each(array, function (i, obj) {
...
});
}
Replace with this:
render_1: function () {
$.each(PG.optionitem, function (i, obj) {
...
});
}
This solution is actually independant from my first one. If you don't want the array in global scope, this solution will work.

Categories