How to use specific data from arrays - Example of click - javascript

I have the following JQuery code:
var test = new Array();
$(".quiz_list_row").each(function(index){
// Gets the data necessary to show game chosen
$quiz_list_id = $(this).data("quizlistId");
$quiz_level_reached = $(this).data("quizlevelReached");
test.push($quiz_list_id,$quiz_level_reached);
$(this).click(function(){
alert("test: "+test);
});
});
The divs (using html5 to send data):
<div class="quiz_list_row" data-quizlist-id="1" data-quizlevel-reached="5">
<div class="inline quiz_list_cell" id="quiz_list_cell_row0_id1">Quiz 1</div>
<div class="inline quiz_list_cell" id="quiz_list_cell_row0_id2">Current level: 5</div>
</div>
<div class="quiz_list_row" data-quizlist-id="2" data-quizlevel-reached="7">
<div class="inline quiz_list_cell" id="quiz_list_cell_row1_id1">Quiz 2</div>
<div class="inline quiz_list_cell" id="quiz_list_cell_row1_id2">Current level: 7</div>
</div>
The problem is that I need to find out how to use the data in the array test when the user clicks on a specific row (I want to use $quiz_list_id and $quiz_level_reached).

Unless there is a specific reason you're extracting the attributes and putting them into an array, I think you're taking some unecessary steps to achieving what you want. Take away the complexity from this, you have access to the data attributes with the .data() method at any time you have access to the elements jQuery object, one of those times is within the click handler itself.
var quizRows = $(".quiz_list_row");
quizRows.click(function(event) {
var self = $(this);
//As the element clicked on has it's data attributes defined
//You would just need to retrieve it when the element is clicked on
var id = self.data('quizlist-id'),
level = self.data('quizlevel-reached');
console.log("id is " + id);
console.log("level is " + level);
}

Related

How can I add the same XML tags multiple times, with different content?

I have some problems with my code. I want to create an XML Document with JQuery / JavaScript. I am now at the point, where I want to create a few Tags and populate them each with the same tags but different content inside the tags.
Here is the code for better understand
function setItems(xmlDoc, channelTag){
const itemList = [];
const itemTitle = xmlDoc.createElement("title");
const itemLink = xmlDoc.createElement("link");
const itemGuid = xmlDoc.createElement("guid");
const itemMediaContent = xmlDoc.createElement("media:content");
const itemMediaDescription = xmlDoc.createElement("media:description");
itemList.push(itemTitle, itemLink, itemGuid, itemMediaContent, itemMediaDescription);
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item);
//Populate the <item> with the tags from "itemList" and content from "jsonObj"
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(itemList[index]).textContent = jsonObj[0].title;
})
}
}
The Output of the code looks like this:
<item></item>
<item></item>
<item>
<title>Something</title>
<guid>Something</guid>
<link>Something</link>
<media:content>Something</media:description>
<media:description>Something</media:description>
</item>
It always populates the last item-Tag but not the ones above. What I want is that every item-Tag has the same child-Tags (e.g. title, link, guid and so on). Is there something i am missing some unique tags or something like that?
Edited:
Here is some minimal HTML and XML. The values for the function "xmlDoc" and "channelTag" just contains some Document Elements, where my items should be appended, like so:
<rss>
<channel>
<title>SomeTitle</title>
<atom:link href="Link" rel="self" type="application/rss+xml"/>
<link>SomeLink</link>
<description>SomeDesc</description>
<item></item>
<item></item>
<item></item>
</channel>
</rss>
<div class="col-5 col-sm-5 col-lg-3 order-2 count">
<a class="guid1"><img class="card-img image1"></a>
</div>
<div class="col-7 col-sm-7 col-lg-5 order-2">
<div class="card-body">
<a class="guid1">
<h5 class="card-title title1 overflow-title"></h5>
</a>
<p class="card-text body1 text-body overflow-body"></p>
<div class="card-body subtitle">
</div>
</div>
</div>
There are several issues with your code but the area we mostly want to focus on is this:
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item); // you're adding a node here
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(... // and here
})
}
Instead of appending nodes multiple times per iteration, you should create and populate your node before add it it to channelTag.
Here's a way your could do it:
// use a "$" sign as a variable name prefix, so you know it's a Document Element and not a regular javascript variable
var $item = xmlDoc.createElement("item");
// you don't need jQuery for this iteration
itemList.forEach(function (item, index) {
$item.appendChild(itemList[index]).textContent = jsonObj[0].title;
});
// if "channelTag" is a Document Element, rename it "$channelTag"
$channelTag.appendChild(item);
Couple things about the code above:
you don't need jQuery, use forEach instead
there is no way telling what type is channelTag. If it is a selector (of type string), use $(selector), but you are using the appendChild() method before, suggesting it's actually a Document Element. In that case you don't need to wrap it with $()
I don't have the context needed to test this code, so no guarantee it'll work out of the box. But try and re-read your code and go through it top-to-bottom. For each variable, describe its type and value. I found that to be helpful when I'm lost in code.

How can I save user input to local storage?

I've made a day planner and realised I never set the input up to save to local storage. I'm not very familiar with saving to local storage and quite frankly don't know where to start, and the examples I'm seeing online are very different from the format of my code so they're hard to follow. Any tips?
$(function(){
$(document).on('click','.edit_btn' , function(){
let editable = $(this).prev('.edit_cont').attr('contenteditable');
if(editable){
$(this).text('edit');
$(this).prev('.edit_cont').removeAttr('contenteditable');
$(this).prev('.edit_cont').removeClass('edit_cont_border');
}
else{
$(this).text('save');
$(this).prev('.edit_cont').attr('contenteditable','true');
$(this).prev('.edit_cont').addClass('edit_cont_border');
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "container" spellcheck="false">
<div class = "row my-row">
<div class = "col my-col col-a1 colorcode" id = "9"> 9am </div>
<div class = "col my-col col-a2 edit_cont" > </div>
<div class = "col my-col col-a3 edit_btn"> edit </div>
</div>
<div class = "row my-row" >
<div class = "col my-col col-b1 colorcode" id = "10"> 10am </div>
<div class = "col my-col col-b2 edit_cont"> </div>
<div class = "col my-col col-b3 edit_btn"> edit </div>
</div> (+6 more rows)
Quite simple to use localStorage. All you have do is, for example:
localStorage.setItem('your_data_key', yourData);
You can choose if you want to store single input's data in a local storage item or the entire form.
If you want to use single item to store data of entire form, one way is to convert the form's data into JSON. Since you are using jQuery, check the answers in: Convert form data to JavaScript object with jQuery It has an answer for doing it in vanilla JS as well.
Object.fromEntries(new FormData(form))
You can use combination of event listeners to save and load data to and from localstorage.
In jQuery, one way would be something like the following.
$(function() {
// storedData = localStorage.getItem('your_data_key');
// Load the stored Data to the form based on the way you have saved it
});
function storeData(e) {
// yourData = ...; // Collect the data how you want
// localStorage.setItem('your_data_key', yourData);
}
$("form").on('submit', storeData);
$("form :input").on('change', storeData);
The above is incomplete, untested and for guidance purpose only.

Jquery Classes and InnerHtml

So what I'm doing is pulling battery voltage and the state of a battery from a Mysql database processing the data in data.php and putting that into a Json array all that is fine. When I get to the Javascript side I get stuck.
2 Questions:
Question 1: How do insert the value into id voltage in html without removing the span?
HTML Code:
<div id="voltState" class="tile-box bg-green">
<div class="tile-header">
Battery Status
<div class="float-right">
<i class="glyph-icon icon-bolt"></i>
Green
</div>
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-database"></i>
<div id="voltage" class="tile-content">
<span>volts</span>
</div>
</div>
</div>
Questions 2: class="tile-box bg-green"> I want to replace with the var status from the Javascript so it looks something like class="tile-box bg-(status var here)">
$(document).ready(function() {
sensorData();
});
function sensorData(){
$.ajax({
type:'GET',
url:"data.php",
data:"json",
success:function(sensor) {
//document.write(sensor);
var volt = sensor[0];
var status = sensor[1];
var date = sensor[2];
document.getElementById('voltage').innerHTML = (volt);
$("#voltState").toggleClass('bg-green bg-(STATUS VAR HERE??)');
},
dataType:'json'
});
}
setInterval(sensorData, 3000);
You can use $("#voltage").append(volt) or $("#voltage").prepend(volt) based on if you want the span before or after the value. In this case I assume you want the span after the volt so you can use the second code. If you would like the value inside a new span you can also use:
$("#voltage").prepend($("").text(volt));
You can store the previous status value in a variable lets say pastStatus. So once you have set
$("#voltState").removeClass('bg-'+pastStatus).addClass('bg-'+status);
pastStatus = status
Note: toggleClass is used when you want to switch between adding and removing the same class. It can't be used in this case since you want to add a class and remove another.
document.getElementById('voltage').appendChild(volt);
or
document.getElementById('voltage').innerHTML = '<span>'+volt+'</span>';

jQuery find not working with object array

This code doesn't work
var next = $("#orders").find(".next");
if (next.length == 1) {
var address = $(next[0]).find(".directionsAddress");
var destination = $(address[0]).text();
}
<div id="orders" class="ui-sortable">
<div id="companyAddress" class="noDisplay">101 Billerica Avenue, North Billerica, MA</div>
<div id="companyPhone" class="noDisplay">9788353181</div><div class="next"></div>
<div class="lat">42.616007</div>
<div class="lng">-71.31187</div>
<div id="section1611" class="sectionMargin borderRad">
<div class="directionsAddress noDisplay">92+Swan+Street+Lowell+MA</div>
It is suppose to find one div with a class of "next" that I know exists on the page, then within that one item of the result set array, there will be one div with a class name of directionsAddress.
The "next" array is coming back with a length of 1, so it looks like the problem is with my $(next[0]).find because the address array is coming back as 0 length and I am making a syntax error of some sort that I don't understand.
This should do what you want. You need to find the parent (or alternatively, the sibling of .next) then try to find the applicable .directionsAddress.
var next = $("#orders").find(".next");
if (next.length == 1) {
var destination = $(next).parent().find(".directionsAddress");
alert($(destination).text());
}
Working fiddle: https://jsfiddle.net/00fgpv6L/

Table with large number of rows is slow to update

I have a page with a very large table (several thousand rows).
The table shows a subset of data specified by certain filters. I need the table to update whenever one of the filters changes.
Basically, there are a few check boxes and a text box, whenever one of these changes I reload the table to display only those rows which fit the criteria specified by the user.
I'm doing this by clearing the table and reloading the rows that match the filters. This works but has proven to be very slow.
Here is my javascript code:
function reloadTable() {
var tablebody = document.getElementById("tablebody");
while(tablebody.hasChildNodes()) tablebody.removeChild(tablebody.firstChild);
filter = new FilterChecker();
for (var i=0;i<rows.length;i++) {
if (filter.isVisible(rows[i]))
addRowToTable(rows[i]);
}
}
Is there a way to make it faster?
Alright, sorry for the delay, but I got wrapped up in work. I came up with a nice set of logic that illustrates what you need.
FIDDLE
I created some simple html to illustrate the point. It contains two drop downs to mimic the filters and 8 data rows to mimic your data grid.
<div id="body">
<select id="filterA" class="filter" name="states">
<option value="filterACT">Connecticut</option>
<option value = "filterAMA">Mass</option>
</select>
<select id="filterB" class="filter" name="towns">
<option value="filterBBT">Big Town</option>
<option value = "filterBST">Small Town</option>
</select>
<div id="grid">
<div class="row filterACT filterBBT">BigTown CT 1</div>
<div class="row filterACT filterBBT">BigTown CT 2</div>
<div class="row filterACT filterBST">SmallTown CT 1</div>
<div class="row filterACT filterBST">SmallTown CT 2</div>
<div class="row filterAMA filterBBT">BigTown MA 1</div>
<div class="row filterAMA filterBBT">BigTown MA 2</div>
<div class="row filterAMA filterBST">SmallTown MA 1</div>
<div class="row filterAMA filterBST">SmallTown MA 2</div>
</div>
</div>
</br>
<hr/>
<div>LOG</div>
<hr/>
<div id="log"></div>
The log div is simply to show an output, which I think would be helpful. Each row is identified by class 'row' followed by another series of classes. These classes help determine what their filter data is. You would need to set this programmatically when building the grid. Additionally, these class names must match the filter option values. You can see that the first row has classes from the first option in filterA and from the first option in filterB.
Now, the javascript is a bit verbose, but you can refactor to your hearts content. Sometimes I find it easier when things are explicit when you are trying to understand them. Also, admittedly, I would do this with jQuery, so my pure Javascript isn't as sharp.
var elements = document.getElementsByClassName('filter');
writeToLog("Filter elements found: " + elements.length);
for(var e = 0;e < elements.length;e++)
{
elements[e].onchange =function() {
writeToLog('Filter event fired for id:'+this.id);
filterChange();
};
}
First I get all the elements with the filter class, this would be your filters. I then iterate over them and set their onchange event to call the filterChange() method. The writeToLog() method calls are just for output purposes.
function filterChange() {
var filterClasses = [];
for(var i = 0;i<elements.length;i++) {
writeToLog('Pushing ('+elements[i].value+') into filter class variable.');
filterClasses.push(elements[i].value);
}
In the first part of the function I get all the select filter option values and put them into an array.
writeToLog('Filter classes: ' + filterClasses);
var rows = document.getElementsByClassName('row')
writeToLog('Row count: ' + rows.length);
I then get all of the rows, in my grid and start to iterate over them:
for(var j = 0;j<rows.length;j++)
{
writeToLog('Checking row: ' + rows[j].className);
var rowIsHidden = false;
Once I have a row, in the loop, I iterate the filter classes in the array and see if this row's classes have it. If not, I set rowIsHidden to true, otherwise it stays false.
for(var k = 0;k<filterClasses.length;k++)
{
writeToLog('Checking for class: ' + filterClasses[k]);
if(rows[j].className.indexOf(filterClasses[k]) < 0)
{
writeToLog('Class not found, hide this row.');
rowIsHidden = true;
break;
}
}
Before the loop moves to the next row, I set the display style based on the rowIsHidden value.
writeToLog('Row is hidden: ' + rowIsHidden);
rows[j].style.display = rowIsHidden ? 'none' : 'block';
}
}
By all means, this can be cleaned up and certainly optimized, but I think the intent and logic is fairly clear. Hope this helps and feel free to question any of it :)

Categories

Resources