Button give score to a variable - javascript

I'm learning html programming and I want to create a "website" (just to try my knowledge). It's very simple. There are two buttons. If you press win, add 1 score to win variable, if you press lose, add 1 score to lose variable. And it writes the scores under the buttons. But I can't make it.
</head>
<body>
<button id="win">Win!</button><button id="lose">Lose</button>
</br>
<script>
var win = 0;
var lose = 0;
function win(){
win = win + 1;
};
function lose (){
lose = lose + 1
};
</script>
</body>
</html>

Add an onclick event to your buttons:
<button id="win" onclick="return win();">Win!</button>
<button id="lose" onclick="return lose();">Lose</button>
You are going to need an element under each button, a div or span, with IDs so that you can change the innerHTML when the numbers are updated. Alter your functions to update the appropriate element.
You also probably want to wrap the buttons and elements in a table.

Something like this-
<html>
<table>
<tr>
<td><button id="win" onclick="win()">Win!</button></td>
<td><button id="lose" onclick="lose()">Lose!</button></td>
</tr>
<tr>
<td id="wins"></td>
<td id="losses"></td>
</tr>
</table>
<script>
var wins= 0;
var losses = 0;
function win() {
wins= wins+1;
document.getElementById('wins').innerHTML= wins;
};
function lose() {
losses= losses+1;
document.getElementById('losses').innerHTML= losses;
};
</script>
</html>

Related

Dynamically add rows and run the script

I have a table that's creating rows dynamically upon button click. This input box contains an auto suggest script. When , I am trying to perform an input on the the first box(the one that is default created) , the auto complete works fine. But, on performing the dynamic adding of the row, the script for that row doesn't work. How to invoke the auto complete script on the new ?
<html>
<body>
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr>
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
{!! Form::text('nameId', null,['class'=>'form-control auto', 'placeholder' => 'name']) !!}
</td>
</tr>
</body>
</table>
<script type="text/javascript">
$(document).ready(function ()
{
$("#add").click(function()
{
$('#tableAdd tr:last').after('<tr><td>{!! Form::text('project_manager_name', null,['class'=>'form-control pmID', 'placeholder' => 'Project Manager']) !!}</td></tr>')
});
});
$(".auto")
.on("keydown", keyDownEventForProjectAndCompetencyLead)
.autocomplete(
{
//function that autocompletes the input
});
</script>
</body>
</html>
Jquery sometimes has a little trouble identifying elements that have been programatically added to the DOM just by the original class / id. Try using a different selector method to check against the modified page:
$(document)
.on("keydown", ".auto", keyDownEventForProjectAndCompetencyLead)
.autocomplete( // etc )
Your selector isn't applying to DOM elements added after the page is loaded.
Modify as above to listen on all element in document that match, or attach listener on each new element created:
<html>
<body>
<button id="add">add</button>
<table id="cooltable">
<tr>
<td>cool table cell</td>
</tr>
</table>
<script type="text/javascript">
function autoPopulate(event){
// some code
event.currentTarget.value = "auto populated content";
}
let add_button = document.getElementById('add');
add_button.addEventListener('click',(event)=>{
let new_row = document.createElement('tr'); // create row
let new_cell = document.createElement('td'); // create cell
let new_input = document.createElement('input'); // create input
new_input.type = 'text';
new_input.value = "default content";
new_input.addEventListener('keydown', (event)=>{ // attach listener
autoPopulate(event);
});
new_cell.appendChild(new_input) // add input to cell
new_row.appendChild(new_cell) // add cell to row
document.getElementById('cooltable').appendChild(new_row); // add row to table
})
</script>
</body>
</html>
Problem here is you are adding callback on "keyDown" event which is not happening hence your script is not running
To fix this you should add eventlistener on jquery load()
Or you should using .bind('DOMNodeInserted DOMNodeRemoved') to call function when new node are added or deleted.
<div id='myParentDiv'> </div>
<button>Click </button>
$("button").click(function(){
$("#myParentDiv").append("<div class='test'></div>");
});
$("#myParentDiv").bind("DOMNodeInserted",function(){
alert("child is appended");
});
Here is working demo
https://jsfiddle.net/vickykumarui/28edcsmb/
Code for Table Example
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr id = "test1">
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
Test 1
</td>
</tr>
</body>
</table>
var numberOFRow = 1;
$("#add").click(function(){
numberOFRow++
$('#tableAdd tr:last').after('<tr id = test'+numberOFRow +'><td> Test' + numberOFRow + '</td></tr>')
});
$("#tableAdd").bind("DOMNodeInserted",function(){
alert("Row number"+ numberOFRow+ "created");
});
Working Demo for your table examplehttps://jsfiddle.net/vickykumarui/qpxL8k4c/

How to find out which button was clicked in handler function

In my code, I need to make it so when button 1 is pressed it sets a number to be "1" and if button 2 is pressed, it sets the number to be 2.
<!DOCTYPE html>
<html>
<body>
<table style="width:65%;height:100px">
<tr><td align="center" id="blockOne">
<p><button onclick="addGraph()" id="buttonOne">Create Graph/Chart</button></p>
<tr><td align="center" id="blockTwo">
<p><button onclick="addGraph()"id ="buttonTwo">Create Graph/Chart</button></p>
</table>
</body>
<script>
var button1 = document.getElementById('buttonOne');
var button2 = document.getElementById('buttonTwo');
var container = "0";
// When the user clicks the button, open the modal
function addGraph() {
{
if (button1.onclick === true) {
container = "1";
}
if (button2.onclick === true) {
container = "2";
}
}
console.log(container);
}
</script>
</html>
You can simply pass a parameter in your addGraph function which can be assigned to container as button1.onclick is not a valid way that gives you a boolean result.
var button1 = document.getElementById('buttonOne');
var button2 = document.getElementById('buttonTwo');
var container = "0";
function addGraph(value) {
container = value;
console.log(container);
}
<table border='1' style="width:65%;height:100px">
<tr><td align="center" id="blockOne">
<p><button onclick="addGraph(1)" id="buttonOne">Create Graph/Chart</button></p></tr>
<tr><td align="center" id="blockTwo">
<p><button onclick="addGraph(2)"id ="buttonTwo">Create Graph/Chart</button></p></tr>
</table>
You can check which button was pressed by passing this as your function parameter.
Then, simply check your element's id and edit container with :
container = elem.id == 'buttonOne' ? "1" : "2";
var container = "0";
// When the user clicks the button, open the modal
function addGraph(elem) {
container = elem.id == 'buttonOne' ? "1" : "2";
console.log(container);
}
<table style="width:65%;height:100px">
<tr>
<td align="center" id="blockOne">
<p><button onclick="addGraph(this)" id="buttonOne">Create Graph/Chart</button></p>
<tr>
<td align="center" id="blockTwo">
<p><button onclick="addGraph(this)" id="buttonTwo">Create Graph/Chart</button></p>
</table>
You can define the function to accept the number as input, and make the onclick function called filled with the dedicated number.
<button onclick="addGraph(1)">Some text</button>
In this case you don't even need to define the button id, if you don't need to manipulate the buttons.
Notice that in your Html you should open and close all the html elements.
In your JavaScript logic you can select multiple elements by their ids with document.querySelectorAll('#buttonOne, #buttonTwo')
Than just iterate over all them with Array.prototype.forEach() to dynamically attach the click event listener and handle the container value like this container = (index + 1).toString();
Code:
let container = '0';
document
.querySelectorAll('#buttonOne, #buttonTwo')
.forEach((el, index) => el.addEventListener('click', () => {
container = (index + 1).toString();
console.log(container);
}));
<table style="width:65%;height:100px">
<tr>
<td align="center">
<p>
<button id="buttonOne">Create Graph/Chart</button>
</p>
</td>
</tr>
<tr>
<td align="center">
<p>
<button id="buttonTwo">Create Graph/Chart</button>
</p>
</td>
</tr>
</table>

Using object reference (this) in called function

I have rewritten this question as parts of the original were solved to a simpler solution:
I have a dynamically created table where there will potentially be over 100 table cells () that wont have ID's for them. When a table cell is clicked a onclick event fires and a conditional check is done to determine if it is the first click of a 2 click series or the second click. The conditional determines which value of 2 hidden form fields is set.
Now here is the simple part im trying to accomplish: onclick, IF it is the first click I want the background color of the object that triggered the function to be color1 else if it is the second click then it will be color2.
The code: (JSFiddle Here)
CSS
#test tr td {text-align:center; border: thin black solid;}
SCRIPT
<script>
var x = 0;
var click = 0;
function res(zz) {
if (click == 0) {document.getElementById('start').value=zz; click = 1;} else
{document.getElementById('end').value=zz; click = 0;}
}
</script>
HTML
<form action="" method="POST">
<input type="hidden" name="start" id="start" value="">
<input type="hidden" name="end" id="end" value="">
<input name="submit" type="submit" value="submit" />
</form>
<div id="starget"></div>
<div id="etarget"></div>
<table width="100%" id="test">
<thead>
<tr>
<th>Tech</th><th>0800</th><th>0900</th><th>1000</th><th>1100</th><th>1200</th>
</tr>
</thead>
<tr>
<td>Bill</td>
<td>XXX</td>
<td onclick="res(0900);"></td>
<td>XXX</td>
<td>XXX</td>
<td onclick="res(1200);"></td>
</tr>
</table>
This change works IF i want the background color between the first click and second click to be the same:
<td onclick="res(0900);this.style.backgroundColor='green';"></td>
This below however does not work, since the calling object () passes no reference of itself (this.style....) to the function, however this is in fact the way i need it to work because i need the conditional check to determine what color to set the background to:
function res(zz) {
if (click == 0) {document.getElementById('start').value=zz; click = 1;this.style.backgroundColor='green';} else {document.getElementById('end').value=zz; click = 0;this.style.backgroundColor='red';} }
You simply need to pass 'this' to the function res
Fiddle here:
http://jsfiddle.net/sifriday/r3jaapj5/2/
HTML:
<td onclick="res(0900, this);"></td>
Corresponding JS tweak:
function res(zz, el) {
if (click == 0) {document.getElementById('starget').innerHTML=zz; click = 1; el.style.backgroundColor='green';} else {document.getElementById('etarget').innerHTML=zz; click = 0;}
}

Javascript - onclick not working

I'm not sure why, but my onclick event for one of my buttons is not working. It's the one I'm using to do the calculations on my form. I have two others, that are functioning correctly, one triggers a print function, and the other redirects to another page.
Here's the Javascript for the 3 buttons:
<script type="text/javascript">
function previewFunction() {
window.location.href = "preview.php";
}
function printFunction() {
window.print();
}
function calculateFunction() {
var e = document.getElementById("limit");
var limit = e.options[e.selectedIndex].value;
var rate = .0075;
var fee = .0025;
var cost = (rate + fee) * limit;
document.getElementById("cost").innerHtml = cost;
}
</script>
The calculateFunction() is the one that's not working.
Here's the HTML for the calculate button / cost span:
<tr>
<th align="center"><input class="buttonStuff" type="button" onclick="calculateFunction()" value="Calculate" /></th>
<th valign="bottom" align="center"><span style="font-size: 20pt;">Cost: </h3><span id="cost" style="text-decoration:underline;">$0.00</span></th>
</tr>
Here's the HTML for the two that do work:
<tr class="container">
<td width="25%" align="center"><input class="buttonStuff" type="button" onclick="previewFunction()" value="Preview" /></td>
<td width="25%" align="center"><input type="button" class="buttonStuff" onclick="printFunction()" value="Print" /></td>
</tr>
Nothing happens when I click Calculate. I'm sure it's something simple I'm overlooking, maybe not.
Thanks for any help you can provide. Let me know if I need to post more code.
Javascript is case sensitive, it's innerHTML, not innerHtml
document.getElementById("cost").innerHTML = cost;
I had a similar issue. I had child.js and a common.js files. In my case, My HTML file was using both the JS files and both of them had a function with the same name,
child.js
function calculateFunction(){...}
and also
common.js
function calculateFunction(){...}
After I remove one of these my code works fine and onclick started working. hope this helps!

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

Categories

Resources