The 'rightbox' section must show the key and value entered in the form after they were stored using sessionStorage.
I tried Chrome, Firefox, Edge, and Opera browsers. The code didn't work on any of them.
Here is the code:
function doFirst() {
var button = document.getElementById('button');
button.addEventListener('click', saveStuff, false);
}
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
sessionStorage.setItem(one, two);
display(one);
}
function display(one) {
var rightbox = document.getElementById('rightbox');
var thedata = sessionStorage.getItem(one);
rightbox.innerHTML = 'Name of variable: ' + one + '<br />Value: ' + thedata;
}
window.addEventListener('load', doFirst, false);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<section id="leftbox">
<form>
<p>(key) One: <input type="text" id="one"></p>
<p>(value) Two: <textarea id="two"></textarea></p>
<p><input type="button" id="button" value="Save"></p>
</form>
</section>
<section id="rightbox">
Nothing yet!
</section>
</body>
</html>
The following block from your code:
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
console.log(one, two);
sessionStorage.setItem(one, two);
display(one);
}
You need to use document.getElementById() instead of just getElementById. That will solve your issue.
Furthemore, you have used document.getElementById() properly in your first function, so make sure to check for errors in the browser console next time before posting a question. That will help you in long run.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Description:
I took a spinning wheel code from Github and edited it and created 2 spinning wheels.
The thing is that when the wheel stops and chooses a number (or letter) it displays it as an alert // alert(value); //. I would like to know how to print the number under the wheel instead of showing it as an alert. I tried document.body.textContent += value; // but it
displays the result on another blank page instead. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<script type="text/javascript" src="src/rouletteWheel.js"></script>
<script type="text/javascript">
$(function(thisis){
var itemsToShow = 100;
var wheel = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
var items = {};
for(var i=0; i < itemsToShow; i++){
items[i] = wheel[i]
}
$('#canvas').rouletteWheel({
items : items,
selected : function(key, value){
alert(value);
},
spinText : 'Ticket Number',
});
});
</script>
<title></title>
</head>
<body style="background-color:black;" ></body>
<canvas id="canvas" width="740" height="740"></canvas>
</body>
</html>
To print the number under the wheel you had to create an html element inside body tag of your web page, for example
<p id="show_alert_value_p"></p>
than in your Js code add this line instead of alert
$('#canvas').rouletteWheel({
items : items,
selected : function(key, value){
//alert(value);
//comment alert and add below line
$('#show_alert_value_p').html(value);
},
spinText : 'Ticket Number',
});
You need to specify or create a HTML element that will hold the value of said wheel.
Something along the lines of...
<div>
<h3> Results are: </h3>
<h3 id="result"></h3>
</div>
And instead of the alert function use something like.
$("#result").text(value)
Overall you should be more specific in you question description and making your script runnable in from of a snippet would help people find a answer for you.
I am trying to build a simple page, which will calculate your stake and work out your return, like a betting shop.
So far, I have it working by hard coding in my odds. But as you will see in my code, I have the odds pulling through in an alert, which works well. My issue is trying to incorporate this variable into my html, I get the output of "NaN", but I have no clue why! My attempt is commented out, but hopefully this is an easy fix, which I just can't see!
My HTML:
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title></title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://localhost:8888/json.json", function(result){
$.each(result, function(i, field){
//create an element and append data attribute to the element - in this case field name
el = $("<div class='bet-block'>" + field.name + field.odds.numerator+"/" + field.odds.denominator + " </div>").data("name", field.name).data("odds", field.odds.numerator+"/" + field.odds.denominator);
//append element to DOM
$(".bets").append( el );
})
//define a click handler for all new elements to display data in a div
$(document).on( "click", ".bet-block", function() {
$(".bet-name").text( $( this ).data("name") );
$(".bet-odds").text( $( this ).data("odds") );
});
});
function calculate_odds() {
var winnings = 0,
betting_amount = $(".stake").val();
var current_odds = $('.bet-odds').text();
// THIS ECHOS CORRECT ODDS
alert(current_odds);
winnings = (2/1) * betting_amount;
// winnings = (current_odds) * betting_amount;
$('.js-winnings').text(winnings);
}
$(document).ready(function() {
$(".stake").keyup(function(){
calculate_odds();
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="bets">
<h1>All Bets</h1>
</div>
</div>
<div class="col-md-4">
<div class="slip">
<h1>My Bet Slip</h1>
<div class="new-bet-slip">
<p><span class="bet-name"></span> to win # <span class="bet-odds"></span></p>
<input class="stake" type="number" name="betting-amount" min="1" max="5">
<div class="bet-return">
<span>£</span><span class="js-winnings">0.00</span>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
My JSON:
[{"name":"name1","odds":{"numerator":10,"denominator":1}},[{"name":"name2","odds":{"numerator":5,"denominator":2}}, [{"name":"name3","odds":{"numerator":2,"denominator":1}}, ]
Thanks in advance!
The JSON data you entered is not formatted properly, check the square brackets and try again. This site is helpful for that purpose: https://jsonformatter.curiousconcept.com/
as #gujefers pointed out: Your current_odds which is declared as:
var current_odds = $('.bet-odds').text();
Returns string refer to http://api.jquery.com/text/
So when you try to do arithmetic operation on string which is * in winnings = (current_odds) * betting_amount; You get NaN (not a number) error.
So the safe bet would be try converting the string value to int. parseInt function converts string to int
for example try this is console:
var a = '1';
var b = parseInt(a);
console.log(typeof(a)); //this will return string
console.log(typeof(b)); //this will return number
I hope this may help you...
$.getJSON("http://localhost:8888/json.json", function(result){
//parse the json & try
var data= jQuery.parseJSON(result);
$.each(data, function(i, field){
//do your action
console.log(field.name)
$.each(field.odds, function(k, level2){
console.log(level2.numerator,level2.denominator)
});
});
});
For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here
I have the Comments handle in my Google App Engine app to display the comments. I want to stop the page from loading if the user (defined as "chooser" here) is not in localStorage.
I get the first 2 alerts: "load event" and chooser: "undefined". Since "chooser" is undefined I expect the else clause to trigger but I don't get the alert in else clause.
Also, the first item in ordered list is displayed but not the rest. So I assume there is an issue with loading of the page. How can I fix this?
class Comments(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<title>Choices</title>
<script type="text/javascript">
function showChoices ()
{
alert("load event");
var chooser = localStorage.getItem("chooser");
alert("chooser: " + chooser);
if (chooser)
{
document.getElementById("topten").style.display="inline";
}
else
{
alert("else triggers");
document.write("get an invitation");
}
}
window.onload = showChoices;
</script>
</head>
<body>
<div class="content">""")
#python code:
query = Users.all()
e = query.fetch(10)
self.response.out.write("""<ol>""")
for item in e:
self.response.out.write("""
<div id="topten" class="title" style="display:none">
<li>%s (<span class="small">%s</span>)</li>
</div>
<hr><br />"""
% tuple([item.choice, item.owner]))
self.response.out.write("""</ol>""")
self.response.out.write("""
</div>
</body>
</html>""")
Are you sure that chooser is undefined and not the string literal "undefined"?
see this fiddle i made