Vote counter in html/js - javascript

I'm fairly new to programming and have been learning HTML, CSS, and Javascript. I'm working on a project involving the upcoming election where a users presses a button (using <form> in html) to vote for a candidate. What I'm having an issue doing is relaying the results. Using either javascript or html, how would I be able to track the amount of times each button is pressed and relay the information later in the webpage that says the number of votes for each candidate and the total number of votes.
EDIT I've messed around with the code a little and here is my current javascript file, I set the program to tell you who you voted for in an alert() message, but the name of the candidate isn't showing up properly...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" >
<title>Election</title>
</head>
<body>
<center>
<h1>2016 Presidential Election</h1>
<h2>Vote Here</h2>
<form>
<button type="button" onclick="clicksubmit()">Click to vote for Trump</button>
<button type="button" onclick="clicksubmit()">Click to vote for Hillary</button>
</form>
<h3>Results:</h3>
</center>
<script src="election.js" type="text/javascript"></script>
</body>
</html>
JS:
function clicksubmit(){
var votehillary = document.getElementById('hillary');
alert("You voted for "+ votehillary);
var votetrump = document.getElementById('trump');
alert("You voted for "+ votetrump);
}

To count your button clicks you can declare a variable for each candidate and increment them on each click. To do so, you need to change your button elements and your result header:
<h3 id="results">
total: 0
trump: 0
hillary: 0
</h3>
<button type="button" id="trump-button">Click to vote for Trump</button>
<button type="button" id="hillary-button">Click to vote for Hillary</button>
In your election.js file you can fetch each button and apply a onClick event to them, incrementing a variable declared when the page is loaded:
var trump = 0;
var hillary = 0;
function refreshResults () {
var results = document.getElementById('results');
results.innerHTML = 'total: ' + (trump + hillary);
results.innerHTML += '<br />trump: ' + trump;
results.innerHTML += '<br />hillary: ' + hillary;
}
document.getElementById('trump-button').addEventListener('click', function () {
trump++;
refreshResults();
});
document.getElementById('hillary-button').addEventListener('click', function () {
hillary++;
refreshResults();
});

Related

Basic JavaScript how to call a function from the HTML page

I have just started JavaScript basics and I'm struggling with this:
HTML page has the following:
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
This page should call the function calcSquare(), which fetches the value of the element, calculate its square, and print in the console: The square of 5 is 25. The HTML page loads the code, so I can refer to the page with the document keyword. My js code is following:
function calcSquare() {
var number = document.getElementById("number").value;
console.log("The square of" + number + "is" number*number);
}
Can someone tell me what is wrong with it? Thank you so much! Beginners struggles...
The problem is with your function itself.
Keep in mind that .value is used with an input element. So you can use .innerHTML or .textContent.
You forgot also the sign + after "is".
Look at this code snippet .
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
<!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.0">
<title>Document</title>
</head>
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
<script>
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
</script>
</body>
</html>
Instead of .value use .innerHTML, and you are missing sign + after "is"
You need to get textContent, and make some changes in your function calcSquare()
function calcSquare() {
var number = document.getElementById("number");
var number = number.textContent;
console.log("The square of" , number , "is" , number*number);
}
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
And if you are use an input-field you make it more dynmaic :) and if the is target an input you can use the .value
Be sure you cast every time your vars into the right type before do math (parseInt, parseFloat etc)
And because you are new on JS please deal with JS Security - it is very important for your future dev..
https://snyk.io/learn/javascript-security/
https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
Try this . Foe elements such as P or Div You have to ue textContent or innerHTML to get the data inside the tag. You missed string concatenation after "is" too
function calcSquare() {
var number = document.getElementById("number").textContent;
console.log("The square of" + number + "is" +number*number);
}
<body>
<p id="number">6</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
<script>

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

Undefined when doing document.write() with button OnClick="counter"

I'm new to programming and would need some help, why the document.write() didn't work and basically the page crashes... Can anyone help me?
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
function showText() {
var x;
var counter;
if ( x === 0) {
counter = 0;
x = 1;
}
counter = counter + 1;
document.write("Times clicked: " + counter);
}
</script>
<body>
<script type="text/javascript">
showText();
</script>
<button onclick="showText();">Click Me!<button>
</body>
</html>
Avoid using document.write
Quoting from the MDN Developer Network documentation page:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So basically, your issue is using document.write after the page has loaded: this will result in deleting the entire content of the page and displaying that string.
Also, your code doesn't work because your count variable is declared inside the showText function, and you're trying to access it outside of it, running into an error.
Solution
To make your code work you should create another element, let's say a <p> element, and display the text inside of it. Here's an example of a correct page:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me!</button>
<p id="txt">Times clicked: 0</p>
<script type="text/javascript">
function showText() {
count++;
text.textContent = "Times clicked: " + count;
}
var count = 0,
button = document.getElementById("btn"),
text = document.getElementById("txt");
button.addEventListener("click", showText);
</script>
</body>
</html>
Check out a live demo here.

Increment variable value of a variable on webpage refresh

I have code which just increments a value by 10 on every button click. I want that code to increment the value whenever I refresh the page. How do I do that?
Here is the code:
<html>
<head>
<script type="text/javascript">
function reveal() {
var val = document.getElementById("outputtext").value;
var result = parseInt(val) + parseInt(10);
document.getElementById("outputtext").value = result;
}
</script>
</head>
<body>
<p> <h3>Click on below button to increase the value by 10<h3> </p>
<button onclick="reveal()"> Increment</button>
<table>
<tr>
<td><textarea id="outputtext">10</textarea></td>
</tr></table>
</body>
</html>
For the title of your question, you might use the following Javascript function to bring up the previous page:
history.back();
as stated in this question on SO: How to emulate browser back button using javascript
If you want to increment a variable on page refresh with Javascript, you should save this variable as a cookie on the users browser:
document.cookie="increment=10";
Either of these links might help you with this: http://www.w3schools.com/js/js_cookies.asp http://www.htmlgoodies.com/beyond/javascript/article.php/3470821
You could do this without cookies, by using a hash (#value) in the URL. Try this code :
<html>
<head>
</head>
<body>
<h3>Click on below button to increase the value by 10<h3>
<button onclick="reveal()"> Increment</button>
<table>
<tr><td><textarea id="outputtext">10</textarea></td></tr>
</table>
<script type="text/javascript">
//Get the last value
var current = parseInt(location.hash.slice(1));
//If it is set, increment it
if(current){
document.getElementById("outputtext").value = current + 10;
location.hash = '#' + (current+10);
}
function reveal() {
var val = document.getElementById("outputtext").value;
var result = parseInt(val) + parseInt(10);
document.getElementById("outputtext").value = result;
//Set the value
location.hash = '#' + result;
}
</script>
</body>
</html>
Note that I moved the javascript to the end of the file, so that #outputtext is already defined when the code gets executed.

NaN error - Dealing with strings and integers

Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.
It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>

Categories

Resources