Jquery Classes and InnerHtml - javascript

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>';

Related

Toggle DIV element

Ok, this seems to be a easy question but I'm not able to get it.
I have index.php and find.php in my project.
In index.php, I'm showing results of list-group items as follows
<div id="showDetails">
</div>
<div id="showList">
//All my list-group items are listed here
</div>
My Ajax returning the list-group as follows
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "find.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I'm returning the values as a HTML link so it looks like this
<div id="showList">
data 1
data 2
data 3
</div>
What I want is when I click data 1 link, I want to show showDetails div with data 1 populated. Then when I click data 2 link, it changes to data 2 in showDetails.
How do I do that?
Probably the information I've provided is not enough but feel free to ask and I'll provide more.
The simplest solution would be to add a click handler to each item that calls a function, passing in the id of the item you want to display.
Within that function, fetch the data for the given item and show it.
function showData(which) {
console.log(`fetch data ${which} here and show it in the data div.`);
document.getElementById('showData').innerHTML = `show data ${which}`
return false; // prevents navigation on the clicked link
}
<div id="showList">
<a onclick="showData(1)" href="#">data 1</a>
<a onclick="showData(2)" href="#">data 2</a>
<a onclick="showData(3)" href="#">data 3</a>
</div>
<div id="showData"></div>

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.

Javascript Need to pull a value from a function within an array

Here is my code:
<script>
window.addEvent('domready', function(){
new Request.Stocks({
stocks: ['SXCL'],
onComplete: function(yahoo){
var result = '';
Array.each(Array.from(yahoo.query.results.quote), function(quote){
result += '<div class="company-ticks"></div>
<span class="company">Steel Excel ({Name})</span>
<span class="sub-info"> - OTC Markets<span> </div> <div><span class="value">
{LastTradePriceOnly}</span><span class="changeup">
<img src="change-up.gif" class="change-img" />{Change}
({ChangeinPercent})</span></div></div>'.substitute(quote);
}, this);
$('stocks').set('html', result);
},
onRequest: function(script){
$('stocks').set('text', 'Loading...');
}
}).send();
// Request.Stocks.element.js
});
</script>
You see where I have the variable {Change]. I need to determine if this variable is a positive or negative value. If it is positive then it should display the class as "changeup" and the image as change-up.gif. If the value is negative then the class displayed should be "changedown" and the image would be change-down.gif
The images are a green arrow up and a red arrow down. The classes make the color altrenate between red and green.
Because this is within an array thats being called using a function I'm not sure how to go about this. I assume I would have to split up my "result" into 3 sections. The section before, the section that sets the class and the image, and then the rest of the result.
Any help would be appreciated.
This uses Javascript with mooTools. It's pulling a stock quote from yahoo.
I made the assumption that the Change variable was a property of the quote object. Otherwise that's an easy fix in the code bellow.
Array.each(Array.from(yahoo.query.results.quote), function (quote) {
quote.changeImage = (quote.Change > 0) ? 'change-up.gif' : 'change-down.gif';
result += '<div class="company-ticks"></div>
<span class="company">Steel Excel ({Name})</span>
<span class="sub-info"> - OTC Markets<span> </div> <div><span class="value">
{LastTradePriceOnly}</span><span class="changeup">
<img src="{changeImage}" class="change-img" />{Change}
({ChangeinPercent})</span></div></div>'.substitute(quote);
}, this);
Please note, producing HTML in the was you are doing is a bit risky and hard to maintain.

How to use specific data from arrays - Example of click

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);
}

Categories

Resources