For my project I have to scan BLE-tags and show their RSSI for proximity.
The output of the BLEs is working with a JavaScript template.
<body>
<div id="header" data-role="header" data-theme="b">
<h1>BLE overview</h1>
</div>
</br>
<div data-role="content" id="home">
Initialize
Start Scan
Stop Scan
</div>
<ul data-role="list-view" class="devices"></ul>
<div data-role="content id="result">
<script type="text/template" id="device"> //start of the schript tag and output of the scanned BLEs
<ul data-role="listview">
<li data-address="{0}">
<h2>{1}</h2>
Connect
<div id="rssiop"> RSSI: <div> // value of the RSSI
</br>
</li>
</ul>
</script>
</div>
The function, which return the value of the rssi is following
function startScanSuccess(obj)
{
console.log("The RSSI value is:" + obj.rssi); // here I see the RSSI value on the console
if (obj.status == "scanResult")
{
console.log("Scan Result");
addDevice(obj.address, obj.name);
}
else if (obj.status == "scanStarted")
{
console.log("Scan Started");
}
else
{
console.log("Unexpected Start Scan Status");
}
}
and this is the function which gives the name and address of the scanned BLE out
function addDevice(address, name)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
console.log("Mein RSSI: " + obj.rssi);
document.getElementById("rssiop").innerHTML = "The RSSI value is:";
var template = $("#device").text().format(address, name);
$devices.append(template);
}
So everything is working and when I put the div-tag above the template script I can see the RSSI. Can anyone figure out why the innerHTML is in the template part not working?
I figured it out:
The Problem was that the innerHTML wasn't working, because I used the append()-command for the list output. I just had to add the rssi parameter to the addDevices function and it worked.
The correct code of the addDevice function:
function addDevice(address, name, rssi)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
var template = $("#device").text().format(address, name, rssi);
$devices.append(template);
}
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
My Issue:
Please help me run this code as it should. I am getting a null form error when typing a City name in the place holder and I'm not sure why I am practicing this code from here: https://webdesign.tutsplus.com/tutorials/build-a-simple-weather-app-with-vanilla-javascript--cms-33893
/*SEARCH BY USING A CITY NAME (e.g. athens) OR A COMMA-SEPARATED CITY NAME ALONG WITH THE COUNTRY CODE (e.g. athens,gr)*/
const form = document.querySelector(".top-banner form");
const input = document.querySelector(".top-banner input");
const msg = document.querySelector(".top-banner .msg");
const list = document.querySelector(".ajax-section .cities");
/*SUBSCRIBE HERE FOR API KEY: https://home.openweathermap.org/users/sign_up*/
const apiKey = "f077e7d6167270fa866a36699ab528fe"; /*REPLACE THIS WITH YOUR API KEY FROM OPENWEATHERMAP.ORG*/
form.addEventListener("submit", e => {
e.preventDefault();
let inputVal = input.value;
//check if there's already a city
const listItems = list.querySelectorAll(".ajax-section .city");
const listItemsArray = Array.from(listItems);
if (listItemsArray.length > 0) {
const filteredArray = listItemsArray.filter(el => {
let content = "";
//athens,gr
if (inputVal.includes(",")) {
//athens,grrrrrr->invalid country code, so we keep only the first part of inputVal
if (inputVal.split(",")[1].length > 2) {
inputVal = inputVal.split(",")[0];
content = el
.querySelector(".city-name span")
.textContent.toLowerCase();
} else {
content = el.querySelector(".city-name").dataset.name.toLowerCase();
}
} else {
//athens
content = el.querySelector(".city-name span").textContent.toLowerCase();
}
return content == inputVal.toLowerCase();
});
if (filteredArray.length > 0) {
msg.textContent = `You already know the weather for ${
filteredArray[0].querySelector(".city-name span").textContent
} ...otherwise be more specific by providing the country code as well 😉`;
form.reset();
input.focus();
return;
}
}
//ajax here
const url = `https://api.openweathermap.org/data/2.5/weather?q=${inputVal}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
const {
main,
name,
sys,
weather
} = data;
const icon = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/${
weather[0]["icon"]
}.svg`;
const li = document.createElement("li");
li.classList.add("city");
const markup = `
<h2 class="city-name" data-name="${name},${sys.country}">
<span>${name}</span>
<sup>${sys.country}</sup>
</h2>
<div class="city-temp">${Math.round(main.temp)}<sup>°C</sup></div>
<figure>
<img class="city-icon" src="${icon}" alt="${
weather[0]["description"]
}">
<figcaption>${weather[0]["description"]}</figcaption>
</figure>
`;
li.innerHTML = markup;
list.appendChild(li);
})
.catch(() => {
msg.textContent = "Please search for a valid city 😩";
});
msg.textContent = "";
form.reset();
input.focus();
});
<!DOCTYPE html>
<html>
<head>
<script src="main.js"></script>
</head>
<body>
<div class="api">
<div class="container">🌞 This demo needs an OpenWeather API key to work. <a target="_blank" href="https://home.openweathermap.org/users/sign_up">Get yours here for free!</a>
</div>
</div>
<section class="top-banner">
<div class="container">
<h1 class="heading">Simple Weather App</h1>
<form>
<input type="text" placeholder="Search for a city" autofocus>
<button type="submit">SUBMIT</button>
<span class="msg"></span>
</form>
</div>
</section>
<section class="ajax-section">
<div class="container">
<ul class="cities"></ul>
</div>
</section>
<footer class="page-footer">
<div class="container">
</div>
<small>Made with <span>❤</span> by George Martsoukos
</small>
<li class="city">
<h2 class="city-name" data-name="...">
<span>...</span>
<sup>...</sup>
</h2>
<span class="city-temp">...<sup>°C</sup></span>
<figure>
<img class="city-icon" src="..." alt="...">
<figcaption>...</figcaption>
</figure>
</li>
</footer>
</body>
</html>
It's because your javascript code is executed before DOM is fully loaded.
So you have two choices, either move
<script src="main.js"></script> as the last item inside body (before </body>)
or place all your javascript code inside:
document.addEventListener("DOMContentLoaded", e =>
{
// your code here
});
so I'm still learning JavaScript and am having an issue with something I am working on. When trying to enter something into two separate text inputs it will only default to the gotError function, nothing is being inserted into the Web SQL and then read back to the list.
The JavaScript:
function openDb() {
db = openDatabase('DName', '1', 'NameV', 2 * 1024 * 1024);
//(Database Name, Version, Display Name, Size )
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS Logs (id unique, person TEXT, place TEXT)");
});
}
document.addEventListener('init', function(event) {
if(event.target.id == 'mylist') {
openDb();
storeItems();
}
});
function gotError() {
alert('Something went wrong.');
}
function gotSuccess() {
storeItems()
}
function storeItems()
{
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Logs", [], listItems, gotError);
});
}
function listItems(rs)
{
var output = '';
var list = document.getElementById('tList');
for(i = 0; i < rs.rows.length; i++)
{
stuff = person && place;
var row = rs.rows.stuff(i);
output += "ons-list-item>" + row.stuff +
"<div class=\"right\"> <ons-button><ons-icon icon=\"trash\"></ons-icon></ons-button></div>" +
"</ons-list-item>";
}
list.innerHTML = output;
}
function addItem()
{
var textbox = document.getElementById("person", "place");
var value = textbox.value;
db.transaction(function(tx)
{
tx.executeSql("INSERT INTO Logs (person,place) VALUES (?,?)", [value], gotSuccess, gotError)
});
textbox.value = "";
fn.load("mylist.html");
}
The HTML:
<template id="mylist.html">
<ons-page id='mylist'>
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="fn.open()">
<ons-icon icon="md-menu"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center">
My List
</div>
</ons-toolbar>
<div>
<ons-input type="text" class="select-input--underbar" id="person" placeholder="Enter person here . . ."></ons-input>
<ons-input type="text" class="select-input--underbar" id="place" placeholder="Enter place here . . ."></ons-input>
<ons-button modifier="large" onclick="addItem()">Add Item</ons-button>
</div>
<ons-list id='tList'>
<ons-list-header>Listed Items:</ons-list-header>
<ons-list-item>
</ons-list-item>
</ons-list>
</ons-page>
</template>
</ons-page>
</template>
Originally the code was supposed to insert have two text inputs that would need to be filled out, a button would be pressed to add them to the list, then display the db contents for person and place. Then each time the page was opened or closed it would re-read the contents of the db and redisplay them on the list.
This is an error:
stuff = person && place;
Because:
You are declaring stuff as a global variable (error in strict mode).
person and place are undeclared
Probably this error is being catch'ed and then gotError is executed. Probably you would have seen that if declared the function with an argument:
function gotError(error) {
console.error('Something went wrong:', error);
}
I'm completly new to js, I know a bit of Python but I get confused combining JS with HTML.
I'm trying convert an array into a HTML dropdown list but I can't seem to get it to work.
<HEAD>
<TITLE>Exercise Arrays</TITLE>
</HEAD>
<BODY>
<script>
var city;
var userInput = [];
while (city !== "stop") {
city = prompt('Please enter a city or type: "stop" to end');
if (city === "stop") {
break;
}
else {
userInput.push(city)
}
}
document.write("<h1>Exercise arrays </h1>")
document.write("<h2> States: </h2>")
document.write("<form><select>" + city + "</select></form>")
</script>
</table>
</BODY>
</HTML>
Loop your list and add option elements to your dropdown. I restructured the static parts to just HTML and access the select via its id here:
var city;
var userInput = [];
while (true) {
city = prompt('Please enter a city or type: "stop" to end');
if (city === "stop") {
break;
}
else {
userInput.push(city)
}
}
// For each item referred to as `city`, add an option
userInput.forEach(city => dropdown.add(new Option(city)));
<h1>Exercise arrays</h1>
<h2> States: </h2>
<select id="dropdown"></select>
Dear Stackers
I am having following issue. I want to make a Website, with only one HTML file, and insert the Content based on which li element got clicked. And a standard text should already be there.
Now my issue is, that it will not change the value="" of id="content". It will not even writeContent for some reason. I am quite sure I am making a simple and fundamental mistake. I know that it is not yet optimized, but I need to get it working like this, before minimizing anything.
You can currently ignore the function writeContent part, since that will do the innerHTML insertion later on. - currently no Errors
function myHome() {
document.getElementById("content").value = "home_content";
writeContent("<p>myHome</p>");
}
function myKontakt() {
document.getElementById("content").value = "kontakt_content";
writeContent("<p>myKontakt</p>");
}
function myTeam() {
document.getElementById("content").value = "team_content";
writeContent("<p>myTeam</p>");
}
function myUber() {
document.getElementById("content").value = "uber_content";
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent() {
var get_content_attribute = document.getElementById("content").getAttribute("value");
if (document.getElementById("content").getAttribute("value") == "home_content") {
} else if (get_content_attribute = "kontakt_content") {
} else if (get_content_attribute = "team_content") {
} else if (get_content_attribute = "uber_content") {
}
}
<div id="menu">
<ul>
<li>Stalinger
</li>
<li>Kontakt
</li>
<li>Unser Team
</li>
<li>Über Uns
</li>
</ul>
</div>
<div id="content" value="home_content">
<p class="content_text">TEXT
</p>
</div>
1.Looks like div can't has value attribute, try to use "data-value"
or something like that and everything will works fine.
2. you are adding to event listeners on every button when using "click" in html and "addEventListener" in js
3. You should use "event.preventDefault()" to prevent page from reloading when pressing ""
<html>
<head></head>
<body>
<div id="menu">
<ul>
<li>Stalinger</li>
<li>Kontakt</li>
<li>Unser Team</li>
<li>Über Uns</li>
</ul>
</div>
<div id="content" data-value="home_content">
<p class="content_text">TEXT
</p>
<script>
function myHome(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"home_content");
writeContent("<p>myHome</p>");
}
function myKontakt(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"kontakt_content");
writeContent("<p>myKontakt</p>");
}
function myTeam(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"team_content");
writeContent("<p>myTeam</p>");
}
function myUber(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"uber_content");
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent(html) {
var div = document.getElementById("content");
var get_content_attribute = document.getElementById("content").getAttribute("data-value");
if(document.getElementById("content").getAttribute("data-value") == "home_content"){
div.innerHTML = html;
} else if(get_content_attribute = "kontakt_content"){
div.innerHTML = html;
} else if(get_content_attribute = "team_content"){
div.innerHTML = html;
} else if(get_content_attribute = "uber_content"){
div.innerHTML = html;
}
}
</script>
</div>
</body>
</html>
this code is working for me, but architecture is pretty ugly, maybe try to read about how frontend frameworks manage this things.
use setAttribute as document.getElementById("content").setAttribute ("value","XXXXXX") – by User: Vinod Louis
Worked like a charm.
You can check updated code:
To assign attribute you need to use setAttribute instead of value
function myHome() {
document.getElementById("content").setAttribute("value","home_content");
writeContent("<p>myHome</p>");
}
function myKontakt() {
document.getElementById("content").setAttribute("value","kontakt_content");
writeContent("<p>myKontakt</p>");
}
function myTeam() {
document.getElementById("content").setAttribute("value","team_content");
writeContent("<p>myTeam</p>");
}
function myUber() {
document.getElementById("content").setAttribute("value","uber_content");
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent() {
var get_content_attribute = document.getElementById("content").getAttribute("value");
alert(get_content_attribute);
if (document.getElementById("content").getAttribute("value") == "home_content") {
} else if (get_content_attribute = "kontakt_content") {
} else if (get_content_attribute = "team_content") {
} else if (get_content_attribute = "uber_content") {
}
}
<div id="menu">
<ul>
<li>Stalinger
</li>
<li>Kontakt
</li>
<li>Unser Team
</li>
<li>Über Uns
</li>
</ul>
</div>
<div id="content" value="home_content">
<p class="content_text">TEXT
</p>
</div>
I want to assign values to inside id how can i do that in Jquery
controller.cs code
public GroupModel Get()
{
IGroupTypeRepository groupTypeRepo = new GroupTypeRepository();
IGroupRepository groupRepo = new GroupRepository();
var model = new GroupModel();
model.GroupTypes = groupTypeRepo.GetAll().ToList();
Guid first = model.GroupTypes.FirstOrDefault().Id;
model.Groups = groupRepo.GetAll().Where(s => s.Type == first).ToList();
return model;
}
I tried like following
function getGroups() {
debugger;
$.getJSON(
"groupvalues",
function (data) {
if (data.GroupTypes != undefined) {
$.each(data.Groups, function (jindex, jvalue) {
debugger;
if (jvalue.Id != undefined) {
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
}
});
}
}
<div class="span9">
<div class="row">
<section id="projects">
</section>
</div>
</div>
<script id="GroupsTemplate" type="text/html">
<ul id="thumbs">
<li class="item-thumbs span3 Dhol">
<span class="font-icon-music"></span>${GroupType.TypeName}<br />
</p></div> </li>
</ul>
</script>
I guess i'm going wrong here in js function
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
I think that instead of this:
${GroupType.TypeName}
you must have only this:
${TypeName}
because the GroupType is the parameter object for the template (implicit).
Hope this helps. Cheers