How to storage values in local storage using jquery? - javascript

How can dynamic values be stored in the local storage?
I have a seat layout. How i can store only the selected seat numbers in the local storage, but not reserved seats?
My code can be seen below:
$(function() {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
var SeatNo = document.getElementById('place').value;
localStorage.setItem('SeatNum', SeatNo);
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function() {
var str = [],
item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>

localStorage is an object within the global 'window' object, and therefore will normally be available throughout your javascript code. It pretty much behaves like a dictionary, you create, retrieve, edit and remove key:value pairs. jQuery will not be necessary.
It is also imporant to remember that localStorage only support string values, and simply saving an array would not work.
// When modifying bookedSeats:
var bookedSeatsCacheString = JSON.stringify(bookedSeats);
localStorage.setItem('bookedSeats', bookedSeatsCacheString);
// Init code:
var bookedSeatsCache = localStorage.getItem('bookedSeats');
var bookedSeats = JSON.parse(bookedSeatsCache);
if(!Array.isArray(bookSeats))
bookedSeats = [];
init(bookedSeats);
EDIT: I edited your code to make this work with localStorage
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
// Init code
var bookedSeatsCache = localStorage.getItem('bookedSeats'),
bookedSeats;
if(typeof bookedSeatsCache === 'string' && bookedSeatsCache.length > 0)
bookedSeats = JSON.parse(bookedSeatsCache);
else
bookedSeats = [];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
var seatNum = $(this).attr('title');
bookedSeats.push(seatNum);
localStorage.setItem('bookedSeats', JSON.stringify(bookedSeats));
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
vertical-align: middle;
list-style: none outside none;
color:white;
font-family:'LatoWeb', 'Lucida Grande', 'Lucida Sans Unicode', Arial, sans-serif;
font-size:13px;
padding-left:28px;
padding-top:14px;
height:35px;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>

Related

Uncaught SyntaxError: Invalid or unexpected token on line 118, but it does take the user value from the database

I am taking the exciting running and tested code with different database. I am able to connect to the database and the file did take user id from the database but when I click on button "click here to begin" nothing happens no error log entry was generated. just the Uncaught SyntaxError: Invalid or unexpected token when inspect (ctrl + shift + i) the file.
<!DOCTYPE HTML>
<?php
require("db.php");
$userid = mysqli_real_escape_string($db_connection, $_GET["user_id"]);
$strSQL = "SELECT * FROM `t01_users` where `a01_userid` = '. $userid.' ";
$result = mysqli_query($db_connection, $strSQL) or die(mysqli_error($db_connection));
if (!$result) {
echo("<p>Error performing query: " . mysqli_error($db_connection) . "</p>");
exit();
}
$row = mysqli_fetch_array($result);
?>
<head>
<title>TEST YOUR KNOWLEDGE</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div>
<div>
<h1 class="text-center">TEST YOUR KNOWLEDGE</h1>
<!-- display course title -->
<p class="text-center" id="course_title">Test quiz</p>
</div>
<div>
</div>
<!-- display quiz score -->
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6 text-right">
<span id="your_score"> </span>
</div>
</div>
<!-- quiz part -->
<div id="quiz_part">
<div>
<img src="images/cubic.png">
</div>
<div>
<p class="text-center">This quiz contains <span id="number_of_question">8</span> questions.<br>
<span class="text-center">
You need to achieve a score of at least <span id="pass_percentage">80</span>% to complete the course.</span>
</p>
</div>
<div class="text-center">
<button id="start_quiz">CLICK HERE TO BEGIN</button>
</div>
</div>
<div class="text-right" id="submit_button_div">
</div>
</div>
</div>
<div id="no_check" title="Invalid answer" style="font-family:Calibri;">Please select an answer before submitting.</div>
<div id="correct" title="This is correct." class="dialog">
<div class="correct_content" style="font-family:Calibri;"></div>
</div>
<div id="incorrect" title="This is incorrect." class="dialog">
<div class="incorrect_content" style="font-family:Calibri;"></div>
</div>
<script>
$(document).ready(function () {
var screenWidth, dialogWidth;
screenWidth = window.screen.width;
if ( screenWidth < 500 ) {
dialogWidth = screenWidth * .95;
} else {
dialogWidth = 500;
}
var userid = <?php echo $userid ; ?>;
var flag = 0;
var score = 0;
var current_question_number = 0;
var current_question = "";
var course_title = "";
var number_of_question = 0;
var pass_percentage = 0;
var progress_url = "";
var pass_remark = "";
var failed_remark = "";
var questions = new Array();
$( "#no_check" ).dialog({ autoOpen: false });
$.getJSON( "questions.json", function(data) {
// note: this getJSON access the file asynchronously. must set value inside the block
course_title = data.course_title;
$("#course_title").html(course_title);
number_of_question = data.number_of_question;
$("#number_of_question").html(number_of_question);
pass_percentage = data.pass_percentage;
$("#pass_percentage").html(pass_percentage);
progress_url = data.progress_url
//alert(progress_url);
pass_remark = data.pass_remark;
failed_remark = data.failed_remark;
for(i=0; i<data.question_list.length; i++){
questions[i]=new Array;
questions[i]["question_number"] = data.question_list[i].question_number;
questions[i]["annotation"] = data.question_list[i].annotation;
questions[i]["question"] = data.question_list[i].question;
questions[i]["type"] = data.question_list[i].type;
questions[i]["instruction"] = data.question_list[i].instruction;
choice = new Array();
for (j=0; j<data.question_list[i].choice.length; j++){
var option = new Array();
option["label"] = data.question_list[i].choice[j].label;
//alert(data.question_list[i].choice[j].label);
option["option"] = data.question_list[i].choice[j].option;
choice[j] = option;
}
questions[i]["choice"] = choice;
questions[i]["answer"] = data.question_list[i].answer;
questions[i]["correct_description"] = data.question_list[i].correct_description;
questions[i]["incorrect_description"] = data.question_list[i].incorrect_description;
questions[i]["correct_comment"] = data.question_list[i].correct_comment; //**********************
questions[i]["incorrect_comment"] = data.question_list[i].incorrect_comment; //************************
}
});
$("#start_quiz").on("click", function(){
$("#your_score").html("YOUR SCORE: " + score + " OUT OF " + number_of_question);
current_question = questions[current_question_number];
if (current_question["annotation"] != "" && flag == 0){
var question_html = "<p><b>Question " + current_question["question_number"] + " of " + number_of_question + "</b></p><br>";
question_html += "<p>" + current_question["annotation"] + "</p>";
$("#quiz_part").html(question_html);
$("#submit_button_div").html("<button id='annotation_continue' style='background-color:#F6761D; color:#FFF; padding:3px 13px; font-weight:bold; border:2px solid #cccccc; margin-right:15px;'>Click to Continue</button>");
}else{
flag = 0;
var question_html = "<p><b>Question " + current_question["question_number"] + " of " + number_of_question + "</b></p><br>";
question_html += "<p><span style='color: red;'>" + current_question["type"] + "</span> " + current_question["question"] + " <b>" + current_question["instruction"] + "</b></p><br>";
for (m = 0; m<current_question["choice"].length; m++){
question_html += "<p> <input type='radio' name='choice' value='" + current_question["choice"][m]["label"] + "'> <span class='radio-content'>" + current_question["choice"][m]["option"] + "</span></p>";
}
$("#quiz_part").html(question_html);
$("#submit_button_div").html("<button id='submit_answer' style='background-color:#F6761D; color:#FFF; padding:3px 13px; font-weight:bold; border:2px solid #cccccc; margin-right:15px;'>SUBMIT</button>");
}
});
$("#submit_button_div").on('click', '#annotation_continue', function(){
flag = 1;
continue_button();
});
// $("#submit_answer").on("click", function(){
$("#submit_button_div").on('click', '#submit_answer', function(){
//current_question_number++;
var answer = current_question["answer"];
var correct_desc = current_question["correct_description"];
var incorrect_desc = current_question["incorrect_description"];
var correct_comment = current_question["correct_comment"]; //************************
var incorrect_comment = current_question["incorrect_comment"]; //************************
var checked_answer = $("input[name='choice']:checked").val();
if (!checked_answer){
//$( "#no_check" ).dialog("open");
dialog = $("#no_check").dialog({
//width: 'auto', // overcomes width:'auto' and maxWidth bug
maxWidth: 200,
height: 'auto',
modal : true,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: {
'OK': function () {
agreed = true;
$(this).dialog("close");
}
},
beforeClose: function () {
return agreed;
}
});
dialog.dialog("open");
}else if(checked_answer == answer){
current_question_number++;
//autoOpen : false,
score++;
// submit the new score to server
$.ajax({
method: "POST",
url: progress_url,
data: { a01_userid: userid, userProgress: score }
});
$("#your_score").html("YOUR SCORE: " + score + " OUT OF " + number_of_question);
$(".correct_content").html("<span style='color:green; font-family:Calibri;'>" + correct_desc + "</span> " + correct_comment); //*****************************
$("#correct").dialog({
width: dialogWidth,
height: 'auto',
position: {my: "center", at: "center", of: window},
modal : true,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: [
{
text: "Continue",
class: 'correct_button',
click: function() {
$(this).dialog("close");
}
}
],
beforeClose: function () {
continue_button();
}
}).prev(".ui-dialog-titlebar").css("color","green");
$("#correct").dialog("open", "position", {my: "center", at: "center", of: window});
}else{
current_question_number++;
$(".incorrect_content").html("<span style='color:red; font-family:Calibri;'>" + incorrect_desc + "</span> " + incorrect_comment); //****************
$("#incorrect").dialog({
width: dialogWidth,
height: 'auto',
position: {my: "center", at: "center", of: window},
modal : true,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: [
{
text: "Continue",
class: 'incorrect_button',
click: function() {
$(this).dialog("close");
}
}
],
beforeClose: function () {
continue_button();
}
}).prev(".ui-dialog-titlebar").css("color","red");
$("#incorrect").dialog("open", "position", {my: "center", at: "center", of: window});
}
});
$("#quiz_part").on('click', '#retry_button', function(){
location.reload(true);
});
function continue_button(){
if (current_question_number == number_of_question){
var percentage = score / number_of_question;
var pass = pass_percentage / 100;
if (percentage >= pass){
passed();
}else{
failed();
}
return false;
}
current_question = questions[current_question_number];
if (current_question["annotation"] != "" && flag == 0){
var question_html = "<p><b>Question " + current_question["question_number"] + " of " + number_of_question + "</b></p><br>";
question_html += "<p>" + current_question["annotation"] + "</p>";
$("#quiz_part").html(question_html);
$("#submit_button_div").html("<button id='annotation_continue' style='background-color:#F6761D; color:#FFF; padding:3px 13px; font-weight:bold; border:2px solid #cccccc; margin-right:15px;'>Click to Continue</button>");
}else{
flag = 0;
var question_html = "<p><b>Question " + current_question["question_number"] + " of " + number_of_question + "</b></p><br>";
question_html += "<p><span style='color: red;'>" + current_question["type"] + "</span> " + current_question["question"] + " <b>" + current_question["instruction"] + "</b></p><br>";
for (m = 0; m<current_question["choice"].length; m++){
question_html += "<p> <input type='radio' name='choice' value='" + current_question["choice"][m]["label"] + "'> <span class='radio-content'>" + current_question["choice"][m]["option"] + "</span></p>";
}
$("#quiz_part").html(question_html);
$("#submit_button_div").html("<button id='submit_answer' style='background-color:#F6761D; color:#FFF; padding:3px 13px; font-weight:bold; border:2px solid #cccccc; margin-right:15px;'>SUBMIT</button>");
}
}
function passed(){
var failed_html = '<div style="width:100%;padding: 1.5vw 0 1vw 0;" class="text-center"> \
<img src="images/success.png" style="width: 70%"> \
</div>';
$("#quiz_part").html(failed_html);
$("#submit_button_div").html("");
}
function failed(){
var failed_html = '<div style="width:100%;padding: 1.5vw 0 1vw 0;" class="text-center"> \
<img src="images/failed.png" style="width: 70%"> \
</div> \
<div style="width:100%;padding: 1vw 0 1vw 0;" class="text-center"> \
<p class="text-center" style="color:#222222;"><b>';
failed_html += failed_remark;
failed_html += '</b></p></div>';
failed_html += '<div style="width:100%;" class="text-center" id="retry_div"> \
<button id="retry_button" style="padding:1vw 3vw; background-color: #293155; font-weight: bold; font-size: 24px; color:#ffffff;" id="start_quiz">CLICK HERE TO RETRY</button> \
</div>';
$("#quiz_part").html(failed_html);
$("#submit_button_div").html("");
}
});
</script>
</body>
</html>
when i click on the error on right corner it shows:
var userid = ***#test.in; //which the userid from the database

How to print the array values in html dom using java script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have created a bus seat layout dynamically ....
and i have selected seats are pushed to array...
and how to print the array values in html DOM.....
below is my html code
<div>
<h2> Choose seats by clicking the corresponding seat in the layout below:</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
below is my css
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
verticle-align:middle;
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
}
below is my js
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
// Add already reserved seats
localStorage.setItem('SeatNum', JSON.stringify(reservedSeat));
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
var selectedSeat = JSON.parse(localStorage.getItem('SeatNum'));
if($(this).hasClass(settings.selectingSeatCss)){
// Add seat in local storage
selectedSeat.push(parseInt($(this).find('a').text()));
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
else{
// Remove seat from local storage
selectedSeat.splice(selectedSeat.indexOf(parseInt($(this).find('a').text())), 1);
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
}
// Logging
console.log('Reserved and selecting seats : ' + JSON.parse(localStorage.getItem('SeatNum')));
});
$('#btnShow').click(function myFunction() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
how to print the array values in html DOM....
i put an alert..
i tried code but that does't work..
i created bus seat layout dynamically i am putting an alert to show the selected seats and all seats but i want to print the selected seat in html Dom....
Take a div in the end of your html
and then put that line where you set the alert
$('#showSit').text(JSON.parse(localStorage.getItem('SeatNum')));

Moving Javascript variables into Html Table

i found this guide to create a stock ticker.
I tried to change it into an html table, but i'm stuck.
So, i created the table, but i have big problems to divide each variable.
What i want to accomplish is a table with this columns order:
Symbol: CompName
Price: Price
Change: PriceIcon + ChnageInPrice
%: PercentChnageInPrice
What i've accomplished for now it's just this, all the content in one column (because of the variable StockTickerHTML i guess)
Full Code Link
Can you please help me?
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerHTML = "";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function () {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function () {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function () {
Price = $(this).text();
});
$(this).find("Change").each(function () {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function () {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText", PriceIcon="up_green";
if(parseFloat(ChnageInPrice) < 0) { PriceClass = "RedText"; PriceIcon="down_red"; }
StockTickerHTML = StockTickerHTML + "<span class='" + PriceClass + "'>";
StockTickerHTML = StockTickerHTML + "<span class='quote'>" + CompName + " </span> ";
StockTickerHTML = StockTickerHTML + parseFloat(Price).toFixed(2) + " ";
StockTickerHTML = StockTickerHTML + "<span class='" + PriceIcon + "'></span>" + parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + " (";
StockTickerHTML = StockTickerHTML + parseFloat( Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%)</span> </br>";
});
$("#dvStockTicker").html(StockTickerHTML);
$("#dvStockTicker").jStockTicker({interval: 30, speed: 2});
});
}
One solution could be this :
(see comments in code)
$(window).load(function() {
StockPriceTicker();
setInterval(function() {
StockPriceTicker();
}, 2 * 1000); // <------ we refresh each 2 seconds
});
// we get the table's body where
// the lines will be inserted.
var $body = $('table tbody');
/*
this will be the cache of
our lines, once they are prepared / transformed
as your need, we will join and insert them
in the body of our table.
*/
var Lines = [];
/*
We define a function in charge of creating the HTML
of each row of hour table, and then push them
in the array defined above "Lines".
*/
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// this is your function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
/*
We create the html to be inserted on each xml loop.
- First : prepare and transform as you need
- Last : use the function we define above "addLine";
*/
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='" + PriceClass + "'>";
htmlSymbol = htmlSymbol + "<span class='quote'>" + CompName + " </span></span>";
htmlPrice = parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// We use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
/*
Once the loop of reading the XML
end, we have pushed all html in the array "Lines".
So now we delete the content of our table's body, and
we fill it with all the lines joined.
*/
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
.GreenText {
color: Green;
}
.RedText {
color: Red;
}
.up_green {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/up.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
.down_red {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/down.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
table {
border: solid;
border-color: #666;
}
td {
padding: 3px;
}
.symbol {
border: solid 3px #DDD;
}
.price {
border: solid 3px aqua;
}
.change {
border: solid 3px yellow;
}
.percent {
border: solid 3px purple;
}
td.price,
td.change,
td.percent {
text-align: right;
}
tbody tr:nth-child(odd){
background-color:#EEF;
}
tbody tr:nth-child(even){
background-color:#AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class='symbol'>Symbol</th>
<th class='price'>Price</th>
<th class='change'>Change</th>
<th class='percent'>%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Masonry sometimes lays out in one column straight line

I have masonry initialized on some "tiles" that include an image. Most of the time I am not having issues but sometimes the tiles lay out in one column when there should be 3 columns. Do you have any idea what the issue might be?
On ready initialization:
$(document).ready(function() {
var $container = $('#news');
$container.masonry({
itemSelector: '.pageNewsItem',
transitionDuration: 0
});
$container.masonry( 'on', 'layoutComplete', function( msnryInstance, laidOutItems ) {debounced = true;} )
});
Dynamically append tiles:
var count = 0;
function placeNewsTiles(news){ //places news tiles
var length = (news.data.length > 20) ? 20 : news.data.length;
var elems ="";
for(var i = 0; i < length; i++){
elems += '<div class="pageNewsItem inactive" id="'+ count + i + '">\
<div class="outerTextWrap">\
<div class="textWrap">\
<a href="' + news.data[i]._url + '">\
<strong>' + news.data[i]._title + '</strong>\
</a>\
<span class="source">' + news.data[i]._source + '</span>\
</div>\
</div>\
<div class="imageWrap"></div>\
<div class="thumbsOverlay" style="display:none">\
<div class="thumbs">\
<div>\
\
\
</div>\
</div>\
<div class="title">\
<div>\
<a href="' + news.data[i]._url + '">\
<div class="theTitle">Read Article</div>\
</a>\
</div>\
</div>\
</div>\
</div>';
getTileImage({total: news.count, i:count + "" + i, url:news.data[i]._url});
}
elems = $(elems);
$('#news').append(elems).imagesLoaded(function(){
//for(var i = 0; i < length; i++) $('.pageNewsItem').removeClass('inactive'); //$('.pageNewsItem').show(1000);
$('#news').masonry( 'appended', elems);
});
newsPage = 0;
count++;
hoverTiles();
}
getTileImage function is called to conduct an ajax call to obtain the tile image. Masonry layout happens on complete:
var cnt = 0;
function getTileImage(args){
var _t = localStorage.getItem("token"),
url = args.url,
i = args.i;
$.ajax({
type: "GET",
url: apiHost+'/api/tileImg?url=' + url + '&token='+_t,
dataType: "json",
success: function(data) {
var img = (data && data.image.src) ? data.img.src : (data && data.image) ? data.image: "";
if(img.indexOf("spacer") > -1|| img.indexOf("blank") > -1 || img === ""){ $('.pageNewsItem#' + i).hide(); }
else $('.pageNewsItem#' + i).find('.imageWrap').append('<img src="' + img + '" />');
},
error: function(e) {
if (e.status == 404) {
//need to get a new token
getToken(getTileImage, url);
}
}, complete: function(){
cnt++;
if ((cnt ==20) || cnt == args.total) {
var $container = $('#news');
$container.imagesLoaded( function() {
$container.masonry( 'layout' );
$('.pageNewsItem').removeClass('inactive');
//$('.pageNewsItem').show();
});
cnt = 0;
}
/*$('#news').imagesLoaded( function() {
$('.pageNewsItem#' + i + ' .thumbs').height($('.pageNewsItem#' + i).outerHeight() - $('.pageNewsItem#' + i + ' .title').height() - 5);
//$('.pageNewsItem').show();
});*/
}
});//end ajax call
}
CSS:
.pageNewsItem {
width: 33.333%;
padding: 10px;
min-height: 150px;
opacity: 1;
transition: opacity 1s ease;
}
#news {
margin-right: 20px;
margin-top: 25px;
}
Try using the console and manually initialize masonry:
$('#news').masonry();
If it is not working, masonry might be already initialized and therefore it's not repositioning the elements. In that case you have to remove masonry from the div and reinitialize it:
$('#news').masonry('destroy');
$('#news').masonry();

Jquery checkbox filtering - repair

I have found a script with jquery filtering that i need.
In that script some item have values of green and some of green and yellow. If you choose colors green and yellow, you get all green and yellow items, and items that are both green and yellow.
I would need to change that so that if i choose green and yellow, i would only get item that are both green and yellow.
I'm not really good at js so i would really appreciate the help.
var byProperty = [], byColor = [], byLocation = [];
$("input[name=fl-colour]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-size]").on( "change", function() {
if (this.checked) byColor.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byColor, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-cont]").on( "change", function() {
if (this.checked) byLocation.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byLocation, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.flowers > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=fl-colour]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
if (byColor.length) {
if (str == "Include items \n") {
str += " " + "with (" + byColor.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byColor){
if(selector === '') {
selector += "[data-category~='" + byColor.id + "']";
} else {
selector += ",[data-category~='" + byColor.id + "']";
}
});
} else {
str += " AND " + "with (" + byColor.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byColor){
if(cselector === '') {
cselector += "[data-category~='" + byColor.id + "']";
} else {
cselector += ",[data-category~='" + byColor.id + "']";
}
});
}
}
if (byLocation.length) {
if (str == "Include items \n") {
str += " " + "with (" + byLocation.join(' OR ') + ")\n";
$($('input[name=fl-cont]:checked')).each(function(index, byLocation){
if(selector === '') {
selector += "[data-category~='" + byLocation.id + "']";
} else {
selector += ",[data-category~='" + byLocation.id + "']";
}
});
} else {
str += " AND " + "with (" + byLocation.join(' OR ') + ")\n";
$($('input[name=fl-cont]:checked')).each(function(index, byLocation){
if(nselector === '') {
nselector += "[data-category~='" + byLocation.id + "']";
} else {
nselector += ",[data-category~='" + byLocation.id + "']";
}
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.flowers > div').filter(selector).show();
} else if (cselector === '') {
$('.flowers > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.flowers > div').filter(selector).filter(cselector).show();
} else {
$('.flowers > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
Link to jsfiddle: http://jsfiddle.net/3gf1j1ec/
This is how you would obtain an intersection of arrays. It uses the Array.prototype.every method to produce the match.
var byProperty = [], byColor = [], byLocation = [];
var intersectionOfColours = function(){
// get an array of the selected colours
var selectedColours = $('form input[name="fl-colour"]:checked').map(function(){
return this.value;
}).get();
// iterate through the flowers and show/hide
$('.flowers .flower').each(function(){
var flowerColours = $(this).data("category").split(' ');
// if all selected colours can be found in flowerColours, we have a match
var match = selectedColours.every(function(thisColour){
return (flowerColours.indexOf(thisColour) !== -1);
});
if (match) {
$(this).show();
} else {
$(this).hide();
}
});
// debug
$('#result').html( JSON.stringify(selectedColours) );
};
$("input[name=fl-colour]").on( "change", intersectionOfColours);
label {
float: left;
clear: left;
}
.flowers-wrap {
width: 100%;
}
.flowers-wrap form {
width: 49%;
float: left;
}
.flower {
background-color: #DEE;
padding: .5em;
margin: 3px;
border: 1px solid gray;
}
.flowers {
width: 49%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id=result></pre>
<div class="flowers-wrap">
<h3>Available Flowers</h3>
<p><strong>Filter flowers by colour:</strong></p>
<form>
<label><input type="checkbox" name="fl-colour" value="red" id="red" />Red</label>
<label><input type="checkbox" name="fl-colour" value="yellow" id="yellow" />Yellow</label>
<label><input type="checkbox" name="fl-colour" value="pink" id="pink" />Pink</label>
<label><input type="checkbox" name="fl-colour" value="purple" id="purple" />Purple</label>
<label><input type="checkbox" name="fl-colour" value="green" id="green" />Green</label>
<label><input type="checkbox" name="fl-colour" value="other" id="other" />Other</label>
</form>
<div class="flowers">
<div class="flower" data-id="aloe" data-category="green small medium africa">Aloe</div>
<div class="flower" data-id="lavendar" data-category="purple green medium africa europe">Lavender</div>
<div class="flower" data-id="stinging-nettle" data-category="green large africa europe asia">Stinging Nettle</div>
<div class="flower" data-id="gorse" data-category="green yellow large europe">Gorse</div>
<div class="flower" data-id="hemp" data-category="green large asia">Hemp</div>
<div class="flower" data-id="titan-arum" data-category="purple other giant asia">Titan Arum</div>
<div class="flower" data-id="golden-wattle" data-category="green yellow large australasia">Golden Wattle</div>
<div class="flower" data-id="purple-prairie-clover" data-category="purple green other medium north-america">Purple Prairie Clover</div>
<div class="flower" data-id="camellia" data-category="pink other large north-america">Camellia</div>
<div class="flower" data-id="scarlet-carnation" data-category="red medium north-america">Scarlet Carnation</div>
<div class="flower" data-id="indian-paintbrush" data-category="red medium north-america">Indian Paintbrush</div>
<div class="flower" data-id="moss-verbena" data-category="purple other small south-america">Moss Verbena</div>
<div class="flower" data-id="climbing-dayflower" data-category="blue tiny south-america">Climbing Dayflower</div>
<div class="flower" data-id="antarctic-pearlwort" data-category="green yellow large antarctica">Antarctic Pearlwort</div>
</div>
</div>

Categories

Resources