So i'm trying to make a realtime button using Javascript and Firebase. Currently I have a working button which is changing the variable in the realtime database from on to off. But the default value isn't saved so when I switch the button off and reload the page it shows that it is on how can I fix this? I also want it to be updated realtime between all the clients
App.js
(function() {
//Get elements
const preObject = document.getElementById('object');
// Create reference
dbRefObject = firebase.database().ref().child('button').child('value')
// Sync changes
dbRefObject.on('value', snap => console.log(snap.val()));
}());
document.addEventListener("DOMContentLoaded", function() {
console.log("test");
});
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
const dbRefObject = firebase.database().ref().child('button')
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
dbRefObject.set({value: true})
console.log('Checked');
} else {
dbRefObject.set({value: false})
console.log('Not checked');
}
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://www.gstatic.com/firebasejs/live/3.1/firebase.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox" id="checkbox" checked>
<div class="slider"></div>
</label>
<script src="app.js"></script>
</body>
</html>
You're reading the data from the database, but not doing anything useful with it yet here:
dbRefObject.on('value', snap => console.log(snap.val()));}
To have the button reflect the state that you store in the database, use this listener to update the button's state:
dbRefObject.on('value', (snap) {
var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.checked = snap.val().value;
})
Related
I am doing an assignment where I make a simple API call using fetch to retrieve an image a of dog by breed. The one issue I can't resolve is that the input value never changes when I try to retrieve an image of a different breed. the default value, which is 'hound', reappears after I press submit. I know I need to attach an onchange event to my input but I am not sure how to write it or how to get the value after the onchange event is triggered. Any help would be greatly appreciated. I originally wrote this with jQuery but decided to rewrite it in vanilla Javascript so that's why there is no jQuery.
I put a '<---' on the line I am struggling with.
P.S I know my code isn't very good, I am new to this.
Javascript
function getJson(breed) {
fetch("https://dog.ceo/api/breed/" + breed + "/images/random")
.then((response) => response.json())
.then((responseJson) => displayResults(responseJson));
}
function displayResults(responseJson) {
const dogImage = responseJson.message;
let breedImage = "";
let container = document.createElement("div");
console.log(dogImage);
breedImage += `<img src="${dogImage}">`;
container.innerHTML = breedImage;
document.querySelector(".results-img").innerHTML = "";
document.querySelector(".results-img").appendChild(container);
}
function submitButton() {
let breedName = document.querySelector("#numberValue").value;
breedName.addEventListener().onchange.value; <---
document.getElementById("dog-input").addEventListener("submit", (e) => {
e.preventDefault();
getJson(breedName);
});
}
submitButton();
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form>
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need an onchange event handler. Currently you're storing the value of the input in breedName when you call submitButton. That means that breedName will never change because it is merely a reference to the value at that moment.
Instead create a reference to the element and read the value property in the submit event handler. That will get the value how it is at the time you submit.
function getJson(breedName) {
console.log(breedName);
}
function submitButton() {
const form = document.querySelector('#dog-form');
const input = document.querySelector('#numberValue');
form.addEventListener('submit', event => {
event.preventDefault();
const breedName = input.value;
getJson(breedName);
});
}
submitButton()
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="dog-form">
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
In my electron app I have a function to clear my input fields on a button press, but after using it I can't click and type into inputs anymore. However, if I open up the inspector window, they work again.
Why does this happen and how do I fix it?
Electron app's main.js:
const { app, BrowserWindow, Menu } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow();
win.loadFile('window_main/index.html');
}
app.on('ready', createWindow);
index.html
<body>
<input type="text" id="testinput" />
<button id="clear">Clear</button>
<script src="index.js" type="text/javascript"></script>
</body>
The problematic bit of JS in index.js:
document.getElementById('clear').addEventListener("click", clear);
function clear() {
if (confirm("Clear all inputs?")) {
document.querySelectorAll('input').forEach((input) => {
input.value = '';
})
}
}
I reproduced your code after removing the script which is not explained why you are using it, anyhow below is a code using jQuery does the trick, this should get you to the right place at least.. if still didn't work with you post a better explanation of your code for a better help...
mark it as answered if it solves your problem....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<input type="text" id="testinput" />
<button id="clear">Clear</button>
<script>
$(document).ready(()=>{
document.getElementById('clear').addEventListener("click", clear);
})
function clear() {
if (confirm("Clear all inputs?")) {
document.querySelectorAll('input').forEach((input) => {
$(input).val('');
})
}
}
</script>
</body>
</html>
The problem was not clearing the inputs, but rather showing the confirm box. I used the following snippet instead:
dialog.showMessageBoxSync(
title: "Clear inputs",
message: "Clear all input boxes?",
type: "warning",
buttons: ["Cancel", "Ok"]
})
And now everything works as expected.
This example prompts for barcode scan, and then places the value into "scan-input" box. This works great for ONE input/ONE button.
My issue is i want to be able to add multiple inputs/buttons, and have the scan then place the value in the corresponding input text box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'/>
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN
</button>
</div>
<script>
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, { engineLocation: engineLocation });
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
const scanInput = document.getElementById("scan-input");
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>#scan:after {display:none;}</style>
</html>`
I want to be able to add multiple buttons/inputs. and have the corresponding button place it into the scan-input spot.
`<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN</button>
<input id="scan-input2" type="text" placeholder="Scan Receiver #2...">
<button id="scan2" onclick="scan()">SCAN</button>`
[text1] [button1] ----- scan places value into text1
[text2] [button2] ----- scan places value into text2
Here's a slightly adapted version of your HTML (using a digit in every id will help us keep things simpler):
<input type="text" id="scan-input1" />
<button type="button" id="scan1">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2">SCAN</button>
Then, in our JavaScript, we can use the following function to send a message to scan-input1 if scan1 is pressed, scan-input2 if scan-2 is pressed, and so on:
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
document.getElementById(`scan-input${num}`).value = "Scan Complete";
});
});
The code above:
Adds a click event listener to every button,
Gets the number from the id of whichever button is clicked,
Uses that number to target the correct input.
The advantage of the solution above is that it scales automatically. As long as you follow the same naming convention for each id (scan3, scan-input3, etc.), every a new button and input will have identical behaviour.
Edit: Your Code
Below, I've inserted my suggestion into your code - only changing the bare minimum:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input type="text" id="scan-input1" />
<button type="button" id="scan1" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input3" />
<button type="button" id="scan3" placeholder="Scan Receiver...">SCAN</button>
</button>
</div>
<script>
let scanInput;
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
scanInput = document.getElementById(`scan-input${num}`);
scan();
});
});
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, {
engineLocation: engineLocation
});
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>
#scan:after {
display: none;
}
</style>
</html>`
I've been having trouble with my javascript code.
<!DOCTYPE html>
<html>
<head>
<title>js-game</title>
<script src="script.js" type="text/javascript"></script>
<script src="story.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="game">
<ul id="output">
<li onclick="main()">Click here to start!</li>
</ul>
<input autofocus id="inputLine" type="text">
<p onclick="" id="enterInput">ENTER</p>
</div>
</body>
</html>
// Variables
var log="<li>Hello</li>";
var lastVar="";
// Functions
function getInput() {
document.getElementById("enterInput").addEventListener("click", function() {
return document.getElementById("inputLine").value;
document.getElementById("inputline").value="";
});
}
function output(output) {
log=log + "<li>" + output + "</li>";
document.getElementById("output").innerHTML=log;
}
function main() {
output("What's your name?");
alert(getInput());
}
As you can probably see I want to get input from a <input type="text"> with the id of inputLine. And a button with the id of enterInput.
But all I get back is undefined, and I've been working on this for a long time, so I'm getting frustrated.
Sorry for bad english.
Try doing it like so:
document.getElementById("enterInput").addEventListener("click", getInput );
function getInput() {
var val = document.getElementById("inputLine").value;
//do something with val
document.getElementById("inputLine").value="";
return val;
}
See this demo
Or to fetch it as a variable with getInput():
document.getElementById("enterInput").addEventListener("click", function(event){
var val = getInput();
alert(val);
});
function getInput() {
var val = document.getElementById("inputLine").value;
document.getElementById("inputLine").value="";
return val;
}
See this demo
I am trying to create tabs with listviews in JQM dynamically on a button click. Currently, I use JS array that contains sample data which will finally be populated via ajax. After research, it seems that I should trigger either trigger("create") or trigger ("refresh"), but apparently, I don't do it correctly. Here's the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>navbar demo</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" src="../JS/nav.js"></script>
</head>
<body>
<button onclick="fillCategories()">Fill</button>
<div id = "decisions" > </div>
</body>
</html>
Javascript:
function fillCategories() {
var navElements = [{"category_sublist_id":"1","category_sublist_name":"Europe"},
{"category_sublist_id":"2","category_sublist_name":"Asia"},
{"category_sublist_id":"3","category_sublist_name":"Americas"}];
var categoriesTabs = $('<div id="categories">')
.attr("data-role","tabs")
.appendTo("#decisions");
var navBar = $("<div>").attr("id","categoriesNames")
.attr("data-role","navbar")
.appendTo("#categories");
var listElements = [{"sublist_row_id":"1","category_sublist_id":"1","sublist_name":"Great Britain"},
{"sublist_row_id":"2","category_sublist_id":"1","sublist_name":"Sweden"},
{"sublist_row_id":"3","category_sublist_id":"1","sublist_name":"France"},
{"sublist_row_id":"4","category_sublist_id":"1","sublist_name":"Germany"}];
$("#categoriesNames").append($("<ul>").attr("id","categoriesUl"));
$(navElements).each(function(){
$("#categoriesUl").append($("<li>")
.attr("value", this.category_sublist_id)
.append($("<a>")
.attr("href", "#sublist"+this.category_sublist_id)
.attr("data-theme","a")
.attr("data-ajax","false")
.text(this.category_sublist_name)));
});
$("#categories").append(navBar).trigger("create");
categorySublistView("categories", "sublist2", listElements);}
function categorySublistView(elementId, listLink, listData) {
var listId = listLink+"id";
var tab = $("<div>").attr("id",listLink)
.addClass("ui-content")
.appendTo("#"+elementId);
var list = $("<ul>").attr("data-role","listview")
.attr("data-inset","true")
.attr("data-icon","false")
.attr("id", listId)
.appendTo("#"+listLink);
$(listData).each(function(){
var li = $("<li/>")
.attr("value",this.sublist_row_id)
.appendTo("#"+listId);
var link =$("<a>")
.attr("href", "#")
.text(this.sublist_name)
.appendTo(li);
});
if ( $('#'+listId).hasClass('ui-listview')) {
$('#'+listId).listview('refresh');
}
else {
$('#'+listId).trigger('create');
}}
edit:
My initial intention was to draw 3 tabs in the navbar which are listviews, which are visible on tab clicks