I'm creating a form, however, when I try to submit the form using onclick event, I get the following error Uncaught ReferenceError: postAcmgForm is not defined at HTMLButtonElement.onclick
I did try including the tag inside the <head> tag and before the </body> tag and still, it doesn't work. The path mentioned in the src element is correct.
Following is the code
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style>
.inline-div {
float: left;
}
</style>
<script language="JavaScript" type="text/javascript" src="../controller/formcontroller.js" /></script>
</head>
<body>
<div class="container-fluid">
<div id="leftDiv" class="inline-div col-md-3">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<form action="../controller/acmg_controller.php" method="POST" target="_blank">
<!--<form method="POST">-->
<div class="form-group">
PMID:
<input type="text" class="form-control form-control-sm" id="pmid" name="pmid">
</div>
<div class="form-group">
ACMG Category:
<select class="form-control form-control-sm" id="ACMG" name="ACMG">
<option value="FUNCTIONAL STUDY | 9">Functional Studies</option>
<option value="ALLELIC | 10">Patients / Allelic data</option>
<option value="CO-SEGREGATION | 11" option="11">Disease co-segregation</option>
<option value="DE NOVO | 12" option="12">De novo mutation</option>
<option value="CASE CONTROL | 13" option="13">Case-control studies</option>
<option value="PHENOTYPE | 14" option="14">Phenotype/family history</option>
</select>
</div>
<div class="form-group">
Evidence Supports:
<select class="form-control form-control-sm" id="Evidence" name="Evidence">
<option value="Supports Benignnes">Supports Benignness</option>
<option value="Supports Pathogenic">Supports Pathogenic</option>
</select>
</div>
<div class="form-group">
<label for="summary">Summary:</label>
<textarea class="form-control" id="text" name="text" rows="8"></textarea>
</div>
<div class="form-group">
<input type = "hidden" name = "genevar" id = "genevar">
<script>
var hashParams = window.location.hash.substr(1).split('&');
var temvarient = hashParams[1].split('=');
var variant = temvarient[1];
var hashParams_ = window.location.hash.substr(1).split('&');
var temgene = hashParams_[0].split('=');
var gene = temgene[1];
//document.write(gene+' '+variant);
document.getElementById('genevar').value = gene + ' ' + variant;
</script>
</div>
<div class="form-group">
<input type = "hidden" name = "mutation" id = "mutation" >
<script>
var hashParams = window.location.hash.substr(3).split('&');
var mutation = hashParams[2].split('=');
var mutationtype = mutation[1];
document.getElementById('mutation').value = mutationtype;
</script>
</div>
<div class="form-group">
<input type = "hidden" name = "vkey" id = "pvkey" >
<script>
var hashParams = window.location.hash.substr(0).split('&');
var temVkey = hashParams[3].split('=');
var vkey = temVkey[1];
document.getElementById('pvkey').value = vkey;
</script>
</div>
<div class="form-group">
</script>
<input type = "hidden" name = "genevar"id = "genevar" >
<script>
var hashParams = window.location.hash.substr(3).split('&');
var mutation = hashParams[2].split('=');
var mutationtype = mutation[1];
document.getElementById('mutation').value = mutationtype;
</script>
</div>
<button type="submit" class="btn btn-primary" onclick="postAcmgForm(this,event);" name="submit">Submit</button>
</form>
</div>
<div id="rightDiv" class="inline-div col-md-9">
<div id="pdfview">
<iframe id="pdfv"
src="...."
height="750px" width="100%">
</iframe>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
The JavaScript code in '/controller/formcontroller.js' is
function postAcmgForm(id,e){
var ACMG = $("#ACMG").val();
alert(ACMG);
$.ajax({
type : 'POST',
url : '../controller/acmg_controller.php',
dataType : 'json',
data: {
ACMG:ACMG
},
success : function(data){
$.each( data, function( key, value ){
$("#"+key).html(value));
alert(key + ":" +value);
});
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log("parse error for searchString");
}
});
}
The code in 'acmg_controller.php' is:
<?php
date_default_timezone_set("America/New_York");
$date= date('Y-m-d');
$result = $_POST['ACMG'];
$result_explode = explode('|', $result);
$data_array = array('ACMG Category' => $result_explode[0],
'ACMG ID' => $result_explode[1],
'Evidence Support' => $_POST["Evidence"],
'Summary' => $_POST["text"],
'Source' => 'PubMed',
'Date'=> $date,
'Source ID' => $_POST["pmid"],
'Vkey' => $_POST["vkey"],
'Gene Variant' => $_POST["genevar"],
'Mutation Type' => $_POST["mutation"] );
Get rid of the language="JavaScript" and don't replace it with anything. Your code looks good otherwise but the language attribute was never implemented in a standard way and was then deprecated.
Related
index.html:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="post" class="set-currency">
<div class="usd">
<label for="usd">USD</label>
<input type="number" name="usd" id="usd">
</div>
<div class="eur">
<label for="eur">EUR</label>
<input type="number" name="eur" id="eur">
</div>
<div class="gbr">
<label for="gbr">GBR</label>
<input type="number" name="gbr" id="gbr">
</div>
<button type="sumbit" class="submit-rates" name="submit-rates">Set Rates</button>
</form>
<br>
<form method="post" name="exchange-currency">
<div class="needed-currency">
<label for="needed">Needed currency</label>
<select name="needed" id="needed">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option value="uan">UAN</option>
</select>
</div>
<div class="base-currency">
<label for="base">Base currency</label>
<select name="base" id="base">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option selected="selected" value="uan">UAN</option>
</select>
</div>
<div class="converted-currency">
<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount">
<label for="calculated">Converted</label>
<input type="number" id="calculated" name="calculated">
<button type="sumbit" name="convert">Convert</button>
</div>
</form>
<script src="script.js"></script>
</body>
</html>`
script.js:
window.addEventListener("load", function () {
console.log("php es una mierda");
let rates = {};
// document.querySelector(".submit-rates").addEventListener("click", function () {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
rates = JSON.parse(this.response);
}
};
xmlhttp.open("GET", "converter.php", true);
xmlhttp.send();
// })
})
converter.php:
<?php
if (isset($_POST['submit-rates'])):
$usdRate = (int)$_POST['usd'];
$eurRate = (int)$_POST['eur'];
$gbrRate = (int)$_POST['gbr'];
// echo "$usdRate $eurRate $gbrRate";
endif;
$rates = [
"usd" => $usdRate,
"eur" => $eurRate,
"gbr" => $gbrRate];
echo json_encode($rates);
file_put_contents("./rates.json", json_encode($rates));
?>
I have to do a currency converter where a user sets the rates, using JavaScript and PHP.
I decided to transfer data through JSON, and it works like this:
the whole thing console logs: {"usd":null,"eur":null,"gbr":null} and when I press "Set Rates" button, nothing changes.
how can I transfer the data with rates properly?
no estas usando json para usar json debes adicionar la libreria jquery
you are not using Json, if you wanna use Json, you should add jquery library
html
<!-- change your button -->
<button type="button" onclick="registroModificacion()">Convert</button>><
<!-- add at the end of yout page. you have to use jquery library -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>
<script>
function registroModificacion(){
//get values of your form by id
const needed = $('#needed').val();
const usd= $('#usd').val();
$.ajax({
url:'paginaEn.php',
type:"POST",
data: {needed:needed,usd:usd},
success:function(r){
alert(r);
},
})
}
</script>
paginaEn.php
<?php
$usd= $_POST['usd'];
$needed= $_POST['needed'];
echo $needed." ".$usd;
?>
I am trying to add a style [text-decoration: line-through] to a value of an object property. How to add the style at javascript code line no 28 closeIssue?
I want to add style to the currentIssue.description.
Here is my code:
document.getElementById('issueInputForm').addEventListener('submit', submitIssue);
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
const issue = { id, description, severity, assignedTo, status }; // issue = object
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
document.getElementById('issueInputForm').reset();
fetchIssues();
e.preventDefault();
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
// How to add a style on "currentIssue.description"
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => issue.id != id)
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3 id="xxx"> ${description} </h3>
<p><span class="glyphicon glyphicon-time"></span> ${severity}</p>
<p><span class="glyphicon glyphicon-user"></span> ${assignedTo}</p>
Close
Delete
</div>`;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Issue Tracker: </title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.lt {
text-decoration: line-through;
}
</style>
</head>
<body onload="fetchIssues()">
<div class="container">
<h1>Issue Tracker: <span id="issue-counter"></span></h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueInputForm">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select id="issueSeverity" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
How can I do that?
man u can try this :
value.style.textDecoration = 'line-through'
I have a small sidebar form that submits user data. It is all functional for anyone in the USA but if someone from overseas tries to submit the form, it fails. I even logged into the same user account as the one overseas and the form submits for me. I have never encountered an issue like this with GAS. The account the user is logged into owns the spreadsheet that the script is housed in and he has tried both local and US IP addresses to submit the data (not sure if this even matters.) What do I need to change/include in my scripts to allow all users to be able to submit the form? Would creating a Webapp and trigger be a fix?
Code.gs
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
//PROCESS FORM DATA
function processForm(formObject){
var notes = [formObject.client,
formObject.website,
formObject.email,
formObject.plan];
var mTabs = [formObject.client,
formObject.plan,
formObject.timeAllowed,
'',
'',
'00:00:00.000'];
pushToSheets(notes,mTabs);
}
//INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
//THIS FUNCTION IS USED TO PUSH DATA TO EACH RESPECTIVE SHEET FROM THE SIDEBAR FORM SUBMISSION
function pushToSheets(notes,mTabs) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var noteTab = ss.getSheetByName('NOTES');
var sheetArr = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEPT','OCT','NOV','DEC'];
// var sheetArr = ['JAN','FEB'];
var nLast = noteTab.getLastRow();
noteTab.insertRowBefore(nLast+1);
noteTab.getRange(nLast+1, 1,1,4).setValues([notes]);
noteTab.getRange(2,1,nLast+1,17).sort([{column: 4, ascending: true}, {column: 1, ascending: true}])
for(var x = 0; x < sheetArr.length; x++) {
var sheet = ss.getSheetByName(sheetArr[x]);
var sLength = sheet.getLastRow();
sheet.insertRowBefore(sLength-1);
sheet.getRange(sLength-1, 1,1,6).setValues([mTabs]);
sheet.getRange(2, 1,sLength,11).sort([{column: 2, ascending: true}, {column: 1, ascending: true}])
}
}
Index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<title>Contact Details</title>
</head>
<body class="bg-secondary text-light">
<div class="container">
<?!= include('Form'); ?> <!-- See Form.html file -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$('#timeAllowed').keypress(function() {
var regex = new RegExp("^[0-9]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if(this.value.length == 2){
this.value = this.value+':';
}
if(this.value.length == 5){
this.value = this.value+':00';
}
if(this.value.length > 7) {
return false;
}
});
</script>
</body>
</html>
Form.html
<form id="myForm" onsubmit="handleFormSubmit(this)" autocomplete="off">
<div class="form-group">
<label for="client">Client</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="clint" name="client" placeholder="Client Name">
</div>
<div class="form-group">
<label for="gender">Plan</label>
<select class="form-control form-control-sm" id="plan" name="plan" required>
<option value="" selected disabled>Choose...</option>
<option value="00 hosting">00 hosting</option>
<option value="01 slim">01 slim</option>
<option value="02 basic">02 basic</option>
<option value="10 special">10 special</option>
<option value="99 coming up">99 coming up</option>
</select>
</div>
<div class="form-group">
<label for="last_name">Time Allowed</label>
<input class="form-control form-control-sm" type="text" class="form-control" pattern="[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" title ="00:00:00" id="timeAllowed" name="timeAllowed" placeholder="00:00:00">
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control form-control-sm" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="website">Website</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="website" name="website">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>
i am very new to web dev and javascript. i am working on a project from a book and building a simple web app that takes orders for coffee. i am using the constraint validation api and i am stuck on that. there is a function that tests the input into the email field against a regular expression and it returns true if the email address has 'authorized email address'. as long as it doesn't match i try to submit the form and i get the expected message '**** is not an authorized email address'. but when it it does match the pattern and the isCompanyEmail function returns true i still get a validity message, just a different one saying 'please match the requested format'. does anyone have any idea what could be causing this? i am including the validation code and form code.
validation code:
(function(window){
'use strict';
var App = window.App || {};
var Validation = {
isCompanyEmail: function(email){
return /.+#bignerdranch\.com$/.test(email);
}
};
App.Validation = Validation;
window.App = App;
})(window);
formhandler code:
(function(window){
'use strict';
var App = window.App || {};
var $ = window.jQuery;
function FormHandler(selector){
if (!selector) {
throw new Error('No selector provided!');
}
this.$formElement = $(selector);
if (this.$formElement.length === 0) {
throw new Error('Could not find element with selector ' + selector);
}
};//end constructor
FormHandler.prototype.addSubmitHandler = function(fn){
console.log('Setting submit handler for form');
this.$formElement.on('submit', function(event){
event.preventDefault();
var data = {};
$(this).serializeArray().forEach(function(item){
data[item.name] = item.value;
console.log(item.name + ' is ' + item.value);
});
console.log(data);
fn(data);
this.reset();
this.elements[0].focus();
});
};
FormHandler.prototype.addInputHandler = function(fn){
console.log('Setting input handler for form');
this.$formElement.on('input', '[name="emailAddress"]', function(event){
var emailAddress = event.target.value;
console.log(fn(emailAddress));
var message = '';
if(fn(emailAddress)){
event.target.setCustomValidity(message);
}else{
message = emailAddress + ' is not an authorized email address!';
event.target.setCustomValidity(message);
}
});
};
App.FormHandler = FormHandler;
window.App = App;
})(window);
and the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>coffeerun</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body class="container">
<header>
<h1>CoffeeRun</h1>
</header>
<section>
<div class="panel panel-default">
<div class="panel-body">
<form data-coffee-order="form">
<div class="form-group">
<label for="coffeeOrder">Coffee Order</label>
<input class="form-control" name="coffee" value="" id="coffeeOrder">
</div>
<div class="form-group">
<label for="emailInput">Email</label>
<input class="form-control" type="email" name="emailAddress" value="" id="emailInput" autofocus required pattern="[a-zA-Z\s]">
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="short">
Short
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="tall" checked>
Tall
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="size" value="grande">
Grande
</label>
</div>
<div class="form-group">
<label for="flavorShot">Flavor Shot</label>
<select id="flavorShot" class="form-control" name="flavor">
<option value="">None</option>
<option value="caramel">Caramel</option>
<option value="almond">Almond</option>
<option value="mocha">Mocha</option>
</select>
</div>
<div class="form-group">
<label for="strengthLevel">Caffeine Rating</label>
<input id="strengthLevel" type="range" name="strength" value="30">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h4>Pending Orders:</h4>
<div data-coffee-order="checklist">
</div>
</div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" charset="utf-8"></script>
<script src="scripts/datastore.js" charset="utf-8"></script>
<script src="scripts/validation.js" charset="utf-8"></script>
<script src="scripts/formHandler.js" charset="utf-8"></script>
<script src="scripts/checklist.js" charset="utf-8"></script>
<script src="scripts/truck.js" charset="utf-8"></script>
<script src="scripts/main.js" charset="utf-8"></script>
</body>
</html>
I'm making an app for the overwolf app contest(http://www.overwolf.com/nvidia-app-challenge/) and in the options page, I want to be able to store the options in localStorage so I can access it from any page, at any time.
Here is my HTML page:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Battle Stats</title>
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="windowManagement.js"></script>
<script>
function toggleDisabled(_checked) {
document.getElementById('warnValue').disabled = _checked ? true : false;
}
//init
var ddl = document.getElementById('options_class');
var length = 5
for (var i = 0; i < length; i++){
if (ddl.options[i].value == localStorage.getItem("options_playerClass")){
ddl.options[i].selected = true;
break;
}
}
function setLocalStorageData()
{
var playerClass = '';
playerClass = document.getElementById("options_class").value;
localStorage.setItem("options_playerClass", playerClass);
alert(localStorage.getItem("options_playerClass"));
}
</script>
</head>
<body>
<div onmousedown="dragResize('BottomRight');">
<div id="content" onmousedown="dragMove();">
<div class="outlined">
<h1>Options</h1>
<form>
<p id="output"></p>
<input type="checkbox" name="options_battleStats" value="Battle Stats">Show Battle Stats<br>
<input type="checkbox" name="options_healthWarning" value="Health Warning" onchange="toggleDisalbled(this.checked);">Low Health Warning
<div class="optionInner">
<p> Warn me at:
<input type="number" name="points" min="0" max="100" step="10" value="30" class="optionValue" id="warnValue">
</p>
<p>Class:
<select name="options_class" id="options_class" class="optionValue">
<option value="smg">SMG</option>
<option value="plasma">Plasma Bomber</option>
<option value="medic">Medic</option>
<option value="rail">Rail</option>
<option value="tesla">Tesla</option>
</select>
</p>
</div>
</form>
</div>
<p>Close<span class="actionButton Middle" onclick="setLocalStorageData();">Save</p></p>
</div>
</div>
</body>
</html>
The error message is:
Uncaught TypeError: Cannot read property 'options' of null
Any help is appreciated!
Your javascript is loaded before the DOM is loaded.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Battle Stats</title>
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="windowManagement.js"></script>
</head>
<body>
<div onmousedown="dragResize('BottomRight');">
<div id="content" onmousedown="dragMove();">
<div class="outlined">
<h1>Options</h1>
<form>
<p id="output"></p>
<input type="checkbox" name="options_battleStats" value="Battle Stats">Show Battle Stats<br>
<input type="checkbox" name="options_healthWarning" value="Health Warning" onchange="toggleDisalbled(this.checked);">Low Health Warning
<div class="optionInner">
<p> Warn me at:
<input type="number" name="points" min="0" max="100" step="10" value="30" class="optionValue" id="warnValue">
</p>
<p>Class:
<select name="options_class" id="options_class" class="optionValue">
<option value="smg">SMG</option>
<option value="plasma">Plasma Bomber</option>
<option value="medic">Medic</option>
<option value="rail">Rail</option>
<option value="tesla">Tesla</option>
</select>
</p>
</div>
</form>
</div>
<p>Close<span class="actionButton Middle" onclick="setLocalStorageData();">Save</p></p>
</div>
</div>
<script>
function toggleDisabled(_checked) {
document.getElementById('warnValue').disabled = _checked ? true : false;
}
//init
var ddl = document.getElementById('options_class');
var length = 5
for (var i = 0; i < length; i++){
if (ddl.options[i].value == localStorage.getItem("options_playerClass")){
ddl.options[i].selected = true;
break;
}
}
function setLocalStorageData()
{
var playerClass = '';
playerClass = document.getElementById("options_class").value;
localStorage.setItem("options_playerClass", playerClass);
alert(localStorage.getItem("options_playerClass"));
}
</script>
</body>
</html>
JavaScript is getting executed prior to dom objects load. Place the entire script block at the end of the page:
<script type="text/javascript">
//All your code here
</script>
</body>
</html>