I am using HTML and JavaScript for a Wi-Fi landing page (called Splash.html). With Splash.html I need to get variable names with document.getElementById and then set name with sessionStorage.setItem. This information is then retrieved by another html page (called Test.html) but when I am redirected to Test.html it replies with "0". I am not an expert but that says to me that the variable names are not being stored properly. Could someone please look at my code and offer some help?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="msapplication-TileColor" content="#0061da">
<meta name="theme-color" content="#1643a3">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<title>
SmartPlay TV
</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="jquery.mCustomScrollbar.css" rel="stylesheet">
<link href="wifi_landing.css" rel="stylesheet">
<script>
var rootPath = "/xxx/";
var defaultImgPath = "/xxx/assets/front/assets/images/products/7.png"
var firstPath = "http://xxx/xxx/";
</script>
</head>
<body>
<div id="login-form-bg-image-tablet">
<img id="back" src="back_5dc4a0740c93eclouds-1586540_960_720.jpg" onerror="this.src = '/xxx/assets/img/tablet.jpg'"></div>
<div class="page">
<div class="page-main">
<div class="row">
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-left">
<div class="row mark-img row-logo">
<div class="col-md-12 mark-img-rect">
<img id="logo" src="logo_5dc4a05f10a24201906271242crop479976885.jpg" onerror="this.src = '/xxx/assets/img/wifilanding-mark.png'"></div>
</div>
<div class="row mark-img row-url">
<div class="col-md-12 mark-mark-rect text-center">
<span id="url" style="word-break: break-word;">www.basicplasticsurgery.com</span>
</div>
</div>
<div class="row">
<div class="col-md-12 textarea-rect" style="display: flex;">
<span id="box_title" class="text3 text" style="padding: 20px 30px; background: white; width: 100%; position: unset; word-break: break-word; border: 2px solid grey;"><p>Welcome to Basic Plastic Surgery!<br><br>Your decision to improve your appearance can be one of the most important investments you make for yourselfâand your self-confidence. Our staff take every measure to ensure that you receive the highest quality care in a professional, comfortable environment.</p></span>
</div>
</div>
</div>
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12 landing-right">
<div class="row">
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12" id="gallery">
<div class="row media-rect">
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload1_5dbb7ff59f88074670796_10219304255335727_5029165459597950976_o.jpg" class="file-rect" id="upload1" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload1_desc">CoolSculpting.
Please see front desk for more info</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload2_5dc4a2905bfdb209508_4516468915805_534071624_o.jpg" class="file-rect" id="upload2" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload2_desc">Me playing soccer.</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload3_5dc4a2976ac89IMG_5313.JPG" class="file-rect" id="upload3" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload3_desc">BPS Background</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload4_5dcddf7d5131a20191017_220631.jpg" class="file-rect" id="upload4" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload4_desc">BPS
Test</span>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-sign-rect">
<div class="landing-sign-rect-form">
<div class="menu1">
<span id="box_text" style="word-break: break-word;">In order to access the internet we need some information. Please submit the following info to use our wifi network.
If you don't submit information you cannot use our network.</span>
</div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name" style="resize:none;" placeholder="First Name">Full Name</textarea></div>
<div class="form-group ">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name1" style="resize:none;" placeholder="Last Name">Email</textarea></div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_email" style="resize:none;" placeholder="Email Address">Tell us what products you're interested in learning about:
</textarea></div>
<div class="form-group text-center">
<!-- <button class = "btn" type = "button" style = "background:#0073c3;color: white;">Sign In</button> -->
<!-- <form method="get" action="$authaction" onsubmit="SubmitFunc()"> -->
<form method="get" action="http://192.168.50.10:2050/nodogsplash_auth/" onsubmit="SubmitFunc()">
<input type="hidden" name="tok" value="$tok"><input type="hidden" name="redir" value="$redir"><input style="background:#0073c3;color: white;" type="submit" value="Sign In"></form>
</div>
<div class="menu3">
Powered by SmartPlay TV
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
It continues with JavaScript section:
<script>
function SubmitFunc() {
sessionStorage.clear();
var name = document.getElementById("user_name").value;
var name1 = document.getElementById("user_name1").value;
var email = document.getElementById("user_email").value;
sessionStorage.setItem("name", name);
sessionStorage.setItem("name1", name1);
sessionStorage.setItem("email", email);
}
function resize(obj) {
obj.style.height = "1px";
obj.style.height = (25 + obj.scrollHeight) + "px";
}
</script>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="jquery.mCustomScrollbar.concat.min.js"></script>
<script src="custom_new.js"></script>
<script src="common.js"></script>
<script src="jquery.validate.js"></script>
<script>
initResize();
function alignTextBox() {
if (jQuery(window).width() < 770) {
jQuery(".media-rect").css("height", "");
jQuery(".textarea-rect .text2").css("min-height", "");
return;
} else {
jQuery(".textarea-rect .text2").css("min-height", "680px");
}
}
function initResize() {
var fileRectObj = jQuery(".file-rect").eq(0);
var width = fileRectObj.width();
var height = width * 9 / 16; // 16:9 to width
jQuery(".file-rect").css("height", height + "px");
alignTextBox();
}
jQuery(window).resize(function() {
initResize();
})
jQuery(document).ready(function() {
jQuery('.autosize').each(function() {
resize(this);
});
});
</script>
</body>
</html>
And here is the Test.html script that includes the getItem part:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Contact Form</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h3 style="margin-top: 100px; text-align: center;">Thank you for your submission. You can now browse the internet freely.</h3>
<script type="text/javascript">
function sendEmail1() {
console.log('sending email');
var name = localStorage.getItem("user_name");
var name1 = localStorage.getItem("user_name1");
var email = localStorage.getItem("user_email");
alert(name + name1 + email);
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'http://192.168.50.10:8000/htdocs/sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {}
};
xhr.send();
}
function sendEmail2() {
console.log('sending email');
var name = localStorage.getItem("name");
var name1 = localStorage.getItem("name1");
var email = localStorage.getItem("email");
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
alert(xhr.responseText);
// return false;
}
};
xhr.send();
}
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
// alert('ready');
// alert(localStorage.getItem("email") + ":" + sessionStorage.getItem("email"));
// alert(sessionStorage.getItem("email") + ":" + localStorage.getItem("email"));
sendEmail1();
});
</script>
</body>
</html>
Test.html is using localStorage instead of sessionStorage.
Related
this is the header which contains the search box and the ul in which the live search results should be showing up. It prints the information about the data items out to the console, which means that the data can be found but it doesn't change anything in the ul which is linked to be altered when search results are found. I also checked the jsonSerialize function and it seems to be correct.
<< ? php
//require_once('../Models/AuctionData.php');
require_once('../Models/AuctionDataSet.php');
$auctionDataSet = new AuctionDataSet();
$auctionDataSet = $auctionDataSet - > fetchSearch($_GET["q"]);
echo json_encode($auctionDataSet);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/my-style.css" rel="stylesheet">
<!--<script src="js/Script.js"></script>-->
<title>Auction Website -
<?php echo $view->pageTitle; ?>
</title>
</head>
<body role="" document ">
<div class="container ">
<div class="row ">
<div id="title " class="col-xs-12 ">
<img src="images/iconhead.jpg "/>
<div class="pull-right "> <h1><?php echo $view->pageTitle ?> </h1></div>
</div>
</div>
<div class="row ">
<div id="menu " class="col-xs-6 col-sm-3 col-md-2 ">
<ul class="nav navbar_default nav-stacked ">
<li>Home </li>
<?php if(isset($_SESSION['id']))
{
echo " <li><a href='Logout.php'>Logout</a></li>"; } else{ echo "
<li><a href='Login.php'>Login</a></li>"; echo "
<li><a href='Register.php'>Register</a></li>"; } ?>
<form><input type="text" class="form-control input-lg" id="search" placeholder="search">
</form>
<ul class="list-group" id="txtHint"></ul>
</ul>
</div>
<script type=application/javascript>
document.addEventListener("DOMContentLoaded", readyPage);
function readyPage() {
let searchIn = document.getElementById("search");
searchIn.addEventListener("keyup", showHint);
console.log("ready");
}
function showHint(event) {
const text = event.target.value;
console.log(event);
let xmlhttp = new XMLHttpRequest();
let uic = document.getElementById("txtHint");
if (text.length > 1) {
xmlhttp.open("GET", "Ajax/ajaxSearch.php?q=" + text);
xmlhttp.send();
return;
}
if (text.length < 2) {
uic.innerHTML = "";
return;
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
let uic = document.getElementById("txtHint");
uic.innerHTML = "";
data.forEach(function(obj) {
console.log(obj);
uic.innerText += '<li class="list-group-item"><p>' + 'obj._id' + 'obj._title' + '</p>';
});
}
};
}
</script>
<div id="content" class="col-xs-6 col-sm-9 col-md-10">
I have created small ethereum dapp. which is working perfectly fine web browser.
http://slenex.com/slenwallet/
But the same is loading in mobile browser but not interacting with mobile wallet
So i tried in metamask browser, but the app is not loading.
Here is my code:
Is anything I have to do, to work in mobile metamask browser?
<!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">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.2.11/web3.min.js" integrity="sha512-6lf28FmolQdo4ap44cXw7j+thYEZzS1/kXxDkX1ppO//SHCageBS1HmYdqkkL819WfGtQ+7TE+uXEwsxjJXEKQ==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body class="container">
<h2 class="row col-lg-12" >PAY ETHER USING WALLET THROUGH SMART CONTRACT</h2><div>
<div class="form-group row col-lg-12">
<input class="col-lg-2 form-control" id="pay" type="text" placeholder="Ether to transfer"/>
<button class="col-lg-1 btn btn-success" id="paySm">Pay</button></div>
<div class="alert alert-success success" role="alert"></div>
</div><hr/>
<h3 class="row col-lg-12" >TRANSFER ETHER</h3><div>
<div class="form-group row col-lg-12">
<input class="col-lg-4 form-control" id="addr" type="text" placeholder="Address"/>
<input class="col-lg-2 form-control" id="amt" type="text" placeholder="Ether to transfer"/>
<button class="col-lg-1 btn btn-dark" id="transfer">Transfer</button></div>
<div class="alert alert-dark tx-success" role="alert"></div>
</div><hr/>
<h3 class="row col-lg-12" >CONTRACT BALANCE </h3><div>
<div class="form-group row col-lg-12">
<button class="col-lg-2 btn btn-warning" id="getBal">Get Balance</button></div>
<div class="alert alert-warning bal-success"></div>
</div>
</body>
<script>
var instance;
var web3;
$(document).ready(function() {
$(".success").hide(); $(".bal-success").hide(); $(".tx-success").hide();
if (typeof web3 !== 'undefined') { // alert("web3 detected");
startApp(web3);
}
function startApp(web3) {
window.ethereum.enable();
web3.eth.defaultAccount = web3.eth.accounts[0];
console.log(web3.eth.defaultAccount)
var rinkebyABI= JSON.parse('[{"inputs":[{"internalType":"address payable","name":"addr1","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"fundtransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"payMe","outputs":[{"internalType":"bool","name":"success","type":"bool"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"balance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]');
EtherContract = web3.eth.contract(rinkebyABI);
var rinkebyInstance = EtherContract.at('0xbB0592720Ed6116dfcda973099E4b484E8D616eB');
// var localABI= JSON.parse('[ { "constant":false,"inputs":[{"name":"addr1","type":"address"},{"name":"amount","type":"uint256"}], "name":"fundtransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false, "inputs":[],"name":"payMe","outputs":[{"name":"success","type":"bool"}],"payable":true,"stateMutability":"payable", "type":"function"},{"constant":true,"inputs":[],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable": false,"stateMutability":"view","type":"function"}]');
// EtherContract = web3.eth.contract(localABI);
// localInstance = EtherContract.at('0xf40D39645F676367D53819537f449A3228c13D5e');
instance = rinkebyInstance;
}
})
$(document).on("click", "#paySm", function(){
var amt = $("#pay").val();
var wei = parseInt(amt)*1e18;
console.log("Amt: "+ amt);
console.log("Default Account: "+ web3.eth.defaultAccount);
console.log("Wei: "+ wei);
instance.payMe({from: web3.eth.defaultAccount, value: wei},
function(err, transactionHash) {
if (!err) console.log("Hash: "+ transactionHash);
$(".success").text("Paid " + amt + " ether to contract");
$(".success").show();
})
});
$(document).on("click", "#transfer", function(){
var addr = $("#addr").val();
var amt = $("#amt").val();
var wei = parseInt(amt)*1e18;
console.log("To Address: "+ addr);
console.log("Wei: "+ wei);
instance.fundtransfer(addr,wei,{from: web3.eth.defaultAccount},
function(err, transactionHash) {
if (!err) console.log(transactionHash);
$(".tx-success").text("Paid " + amt + " ether to " + addr + " Address" );
$(".tx-success").show();
})
});
$(document).on("click", "#getBal", function(){
instance.balance({from: web3.eth.defaultAccount}, function(err, balance) {
if (!err) console.log(balance);
$(".bal-success").text("Available balance in contract: " + balance/1e18 + " Ether");
$(".bal-success").show();
})
});
</script>
</html>
Kindly Help me. Thanks in advance..
Metamask Mobile app requires that the website have a valid ssl certificate. So just make sure to use https:// rather than http:// when accessing your dapp. Please refer to your specific server config in order to enable https://.
I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.
I'm using the latest chrome browser version.
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button type="button" class="btn btn-danger" id="danger">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);
let inner_form = document.getElementById('form').innerHTML;
function open_google() {
window.open('http://google.com', '_blank');
}
let buttons;
function button_change(button) {
switch(button) {
case "success":
buttons = document.getElementsByClassName('btn');
buttons[1].innerHTML = 'Add form';
buttons[1].className = 'btn btn-success';
document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
break;
case "danger":
buttons = document.getElementsByClassName('btn');
buttons[1].innerHTML = 'Delete form';
buttons[1].className = 'btn btn-danger';
break;
default:
break;
}
}
function delete_function() {
let element = document.getElementById('form');
while (element.firstChild) {
element.removeChild(element.firstChild);
}
button_change("success");
}
function add_function() {
document.getElementById('form').innerHTML = inner_form;
button_change("danger");
}
Example code: https://codepen.io/anon/pen/xNjPYj
The event listeners aren't being removed, so both functions are being called (potentially multiple times) depending on how many times the buttons are clicked.
Personally, I think it would be easier to create two buttons, each with independent click handlers, and hide/show them according to which one was clicked.
However, to resolve the current issue in your code, you'll need to remove the previous event listener using removeEventListener() before attaching the new one.
Why don't you just hide it? This is much easier
function toggle() {
var element = document.getElementById("form");
if (element.style.display === "none") {
element.style.display = "block";
}
else {
element.style.display = "none";
}
}
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button onclick="toggle()" type="button" class="btn btn-danger" id="danger">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
</body>
</html>
The main issue with your code was that the event listeners kept getting added but not removed, this caused them to pile up and run unpredictably. I added a function that determines what state the button is in and performs the correct function add_function or remove_function.
I also changed a few minor things
Now usesinnerHTML to textContent where possible for security
Button classes are updated using button.classList.add and button.classList.remove
The button is found using an ID instead of an unreliable classname
The button is held in a variable instead of continuing the look for it
Removed the button_change function because it was difficult to refactor
https://codepen.io/anon/pen/BexJZW
JavaScript:
document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
let inner_form = document.getElementById('form').innerHTML;
let add_delete_button = document.querySelector('#add-delete-button');
add_delete_button.addEventListener("click", on_add_delete_clicked);
function open_google() {
window.open('http://google.com', '_blank');
}
function on_add_delete_clicked() {
let is_adding = add_delete_button.classList.contains("btn-success");
if (is_adding) {
add_function();
} else {
delete_function();
}
}
function add_function() {
const button = add_delete_button;
document.getElementById('form').innerHTML = inner_form;
// Update button
button.textContent = 'Delete form';
button.classList.remove("btn-success");
button.classList.add("btn-danger");
}
function delete_function() {
let element = document.getElementById('form');
while (element.firstChild) {
element.removeChild(element.firstChild);
}
// Update button
const button = add_delete_button;
button.textContent = 'Add form';
button.classList.remove("btn-danger");
button.classList.add("btn-success");
}
HTML:
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button type="button" class="btn btn-danger" id="add-delete-button">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
This implementation will do the text and context switching you desire.
function action(mouseevent) {
const button = mouseevent.target;
let element = document.getElementById('form');
if(element.firstChild) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
button.innerHTML = 'Add form';
button.classList.remove('btn-danger');
button.classList.add('btn-success');
} else {
document.getElementById('form').innerHTML = inner_form;
button.innerHTML = 'Delete Form';
button.classList.add('btn-danger');
button.classList.remove('btn-success');
}
}
Lately I've been having terrible trouble trying to get audio to play on my android device via my phonegap build. I've seen many others have had several issues (mainly pertaining to the correct file path) but none of the solutions I've come across have led to a result. Here is my script for loading and playing the audio:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Audio</title>
</head>
<body>
<div class="container-fluid">
<div class="col-xs-12 col-md-12">
<div class="s-it">Tap Here</div>
</div>
<div class="row">
<div class="col-xs-4 col-md-4"></div>
<div class="col-xs-4 col-md-4">
<div class="container">
<span style="display:none;" id="vX"></span>
<span style="display:none;" id="vY"></span>
<span style="display:none;" id="vZ"></span>
</div>
<div class="row">
<div class="col-md-12 col-xs-12">
<div id="sbell">
<img src="img/bell.png">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12">
<div class="s-text">Test</div>
</div>
<div class="col-md-12 col-xs-12">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12"><br><br></div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12"><br><br></div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="well">
<span class="sts">
<img src="img/shake-banner.png">
</span>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
var myMedia1 = null;
var myMedia2 = null;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady () {
var src1 = '';
var src2 = '';
if (device.platform == 'Android') {
src1 = '/android_asset/www/audiomp3/audio1.mp3';
src2 = '/android_asset/www/audiomp3/audio2.mp3';
}
myMedia1 = new Media(src1, onSuccess, onError);
myMedia2 = new Media(sec2, onSuccess, onError);
myMedia1.addEventListener('ended', function () {
setTimeout(function () {
$('#sbell').removeClass('animate-bell');
}, 2000);
setTimeout(function () {
$('.s-text').fadeOut(200);
}, 500);
}, false);
}
function onSuccess () {
alert("Audio Loaded");
}
function onError (e) {
alert(e.message);
}
window.ondevicemotion = function (event) {
var accX = event.accelerationIncludingGravity.x;
var accY = event.accelerationIncludingGravity.y;
var accZ = event.accelerationIncludingGravity.z;
if (accX >= 8 || accX <= -8) {
myMedia2.play();
}
document.getElementById('vX').innerHTML = accX;
document.getElementById('vY').innerHTML = accY;
document.getElementById('vZ').innerHTML = accZ;
};
$(document).ready(function () {
$('#sbell').click(function(event){
$(this).addClass('animate-bell');
$('.s-text').css('color', 'red').fadeIn(300);
myMedia1.play();
});
});
</script>
</body>
#ZyOn (deleted previous comment)
You can use my Media Demo example to find your issue.
Phonegap Demo Apps (core)
The source is on github. It contains sound samples too. I have additional notes, if you need them.
Also, your app.initialize() should be called AFTER the deviceready event.