Javascript event handler is not working - javascript

I am trying to to increment/decrement a value in a paragraph when a button is clicked.
$(document).ready(function() {
var breakTime = 5;
var section = 25;
var start = "Start";
var stop = "Stop";
function Pomodoro(element, target) {
this.element = element;
this.target = target;
};
Pomodoro.prototype.incrementer = function incrementer() {
// this takes care of break and section timers incrementing
this.element.click(function() {
breakTime++;
var el = this.target;
el.html(breakTime);
});
};
// end
Pomodoro.prototype.decrementer = function decrementer() {
// this takes care of break and section timers incrementing
breakerDec.element.click(function() {
breakTime--;
var el = breakerDec.target.html(breakTime);
});
};
// end
var breakerInc = new Pomodoro();
var ele = $("#inner1");
var tar = $("#par");
breakerInc.element = ele;
breakerInc.target = tar;
breakerInc.incrementer.bind(breakerInc);
//end
var breakerDec = new Pomodoro();
breakerDec.element = $("#inner2");
breakerDec.target = $("#par");
breakerDec.decrementer();
var sectionInc = new Pomodoro($("#inner3"), $("#par2"));
sectionInc.incrementer.bind(sectionInc);
});
and i am getting no result when i click the button.
this is the 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">
<title>Pomodoro Timer</title><!-- End of Title -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="div div-1"><p id="par" class="breaktime-1">5</p>
<div class="inner-div inner-1"><button id="inner1" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner2" type="button" class="btn">-</button></div>
</div>
<div class="div div-2"><p id="par2" class="breaktime">25</p>
<div class="inner-div inner-1"><button id="inner3" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner4" type="button" class="btn">-</button></div>
</div>
</div>
<div class="div div-3">
<h3 class="heading">section</h3>
<button type="button" class="btn-Start-Stop"></button
</div>
<div><p></p></div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

Here is one (trimmed-down) solution just using vanilla javascript:
function changeValue() {
var breaktime = this.parentNode.getElementsByClassName('breaktime')[0];
var val = breaktime.innerHTML;
if (this.className === 'increment') {
val++;
}
else if (this.className === 'decrement') {
val--;
}
breaktime.innerHTML = val;
}
function startStop() {
var values = [];
var breaktimes = document.getElementsByClassName('breaktime');
breaktimes[1].classList.toggle('decrementing');
if (breaktimes[1].classList.contains('decrementing') === true) {
values[1] = parseInt(breaktimes[1].innerHTML);
values[1]--;
breaktimes[1].innerHTML = values[1];
var decrementer = setInterval(function(){
values[0] = parseInt(breaktimes[0].innerHTML);
values[1] = parseInt(breaktimes[1].innerHTML);
if (breaktimes[1].classList.contains('decrementing') !== true) {
clearInterval(decrementer);
}
values[1]--;
breaktimes[1].innerHTML = values[1];
if (values[1] === values[0]) {
window.alert('The counter has reached ' + values[1]);
clearInterval(decrementer);
}
}, 1000);
}
}
var buttons = document.getElementsByTagName('button');
var startStopButton = buttons[(buttons.length -1)];
for (var i = 0; (i+1) < buttons.length; i++) {
buttons[i].addEventListener('click',changeValue,false);
}
startStopButton.addEventListener('click',startStop,false);
<section>
<div>
<p class="breaktime">5</p>
<button id="inner1" type="button" class="increment">+</button>
<button id="inner2" type="button" class="decrement">-</button>
</div>
<div>
<p class="breaktime">25</p>
<button id="inner3" type="button" class="increment">+</button>
<button id="inner4" type="button" class="decrement">-</button>
</div>
<div>
<h3>Section</h3>
<button type="button" class="btn-Start-Stop">Start / Stop</button>
</div>
<div>
<p></p>
</div>
</section>

If you'd like to implement logic using constructors, you can bind events inside of initialization of your instance.
Here is reworked your code based on your html. But code could be improved, so Pomodoro instance can be able not only to decrease or increase, but do both functions.
Also some template engine can give you ability to easy define amount of increase/decrease blocks you want to add to your page.

Related

Dark mode script only works if script is in the index

I have 2 pages, each with the same code for the dark mode button.
The script on the index works, but the script in a different file doesn't. There are no errors.
Here is the script that doesn't work.
<body id = "body" class = "">
<h1 id="h1">Learn Chemistry!</h1>
start skill test
<form >
<h3 id="question"></h3>
<label for = "CO">CO:</label>
<input type = "text" id = "CO" class='input' autocomplete="off" placeholder="Answer">
<label for = "cb">Cl4Br5:</label>
<input type = "text" id = "cb" class='input' autocomplete="off" placeholder="Answer">
</form>
<button id = "check" onclick ="check()">Show answers</button>
<p id='demo'></p>
<form action='coming.html'>
<button id="next" onclick="next()">next</button>
</form>
<form action='index.html'>
<button id = "back" >back</button>
</form>
Here is the dark mode code in the same script.
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<script src="script.js"></script>
Here is the Js function darkmode. (works only for the script in the index)
const labels=document.getElementsByTagName("labels")
const answers=document.getElementById("demo");
const content=document.getElementById("content");
const body = document.getElementById("body");
const heading1 = document.getElementsByTagName("h1")[0];
const heading3 = document.getElementsByTagName("h3")[0];
const buttons = document.getElementsByTagName("button")
const titles = [heading1, heading3,answers]
const time=document.getElementById("time");
const button = document.getElementById("dark-btn");
// console.log(labels.length);
let dark = false;
function darkMode() {
if (dark == false){
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "darks");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "dark-txt");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "dark-txt");
i++;
}
body.setAttribute("class", "dark");
button.style.backgroundColor = "white";
button.style.color = "rgb(88, 119, 255)";
time.style.color = "white"
content.style.color="greenyellow"
dark = true;
} else {
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "");
i++;
}
body.setAttribute("class", "");
dark = false;
button.style.backgroundColor = "rgb(88, 119, 255)";
button.style.color = "white";
content.style.color="green"
}
}
#john
Here is the page that works. It is in the index.
<html >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body id = "body" class = "">
<h1 id='h1'>Learn Chemistry!</h1>
<style>
#content{
color: green;
transform:translate(140px,30px);
line-height:6px;
font-family:sans-serif;
}
</style>
<img id="flask" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<img id="flasktwo" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<button type="button" id="time"
onclick="document.getElementById('date').innerHTML = Date()">
Date and Time.</button>
<p id="date"></p>
<form >
<button id="learn" name="learn"onclick="nextc();return false" >Learn</button>
</form>
<img class="example" src="c2.png">
<h3 id="title"></h3>
<p id="content"></p>
<button id="next" name="hi" onclick="nextc();return false" >Next</button>
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<p id='demo'></p>
<!-- CONCEPTS -->
<!-- <body id = "body" class = ""> -->
<h3 class="title"></h3>
<button id="back">back</button>
<form id='next' action='q2.html'>
<button id="nexttwo" name="nexttwo" onclick="next()">Test</button>
</form>
<script src="script.js"></script>
</body>
</html>

Function that assigns new value appears to initially work the first time, but doesn't appear to return to beginning of if statement the second time

I am in the middle of the Pig Dice problem and I am trying to use the function switchPlayers() to switch between player1 and player2. When clicking "Roll Dice", it appears to switch to the second player but then no longer switches to the first player. After re-working it a few times, I'm starting to think the issue may be that even if Player2 updates to .isTurn = false the function is longer being called? I appreciate any pointers here (Note, haven't worked on the New Game or Hold Button yet)Thank you!
JSFiddle
//business logic for dice
function Dice() {
this.diceValue = 1;
this.roll = 0;
}
function Player() {
this.score = 0;
this.dice = new Dice()
this.isTurn = true
}
//global Players
player1 = new Player();
player2 = new Player();
function switchPlayers() {
if (player1.dice.roll === 0) {
player1.isTurn = false;
} else if (player2.dice.roll === 0) {
player2.isTurn = false;
}
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random() * 6) + 1);
if (this.diceValue === 1) {
this.roll = 0;
} else {
this.roll = this.diceValue;
}
}
Player.prototype.calcScore = function() {
this.dice.rollDice()
if (this.dice.roll === 0) {
switchPlayers();
} else {
this.score += this.dice.roll
}
}
//ui logic
$(document).ready(function() {
$("button.btn-roll").click(function(event) {
if (player1.isTurn !== false) {
player1.calcScore();
$('#p1-total').html(player1.score);
$('#p1-roll').html(player1.dice.roll);
} else if (player2.isTurn === true) {
player2.calcScore();
$('#p2-total').html(player2.score);
$('#p2-roll').html(player2.dice.roll)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-1-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player1-score">
<p>this roll points: <span id="p1-roll"></span></p>
<p>
total: <span id="p1-total"></span>
</p>
</div>
</div>
</div>
<div class="player-2-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player1-score">
<p>this roll: <span id="p2-roll"></span></p>
<p>
total: <span id="p2-total"></span>
</p>
</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>
Keeping your logic, i have reviewed your code, added some tips (button hold), so you could easily understant what i have done and increase yours skills:
function initGame(){
//selectRandomly wich players begins
idToPlay = Math.floor((Math.random()*maxNumberPlayers));
for(let p = 0;p < maxNumberPlayers;p++){
let id = '#p' + p;
$(id + '-action').html('');
$(id + '-name').text(players[p].name);
$(id + '-total').html(players[p].score);
$(id + '-roll').html('--');
$(id + '-round').html('--');
$(id + '-dice').html('--');
}
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
//business logic for dice
function Dice() {
this.diceValue=1;
this.roll=0;
this.round=0;
}
function Player(name) {
this.name = name
this.score = 0;
players.push(this);
}
//global Players
players = [];
new Player("John");
new Player("Peter");
maxNumberPlayers = players.length;
dice = new Dice();
idToPlay = -1;//first player will be choosen by initGame
function switchPlayers() {
displayResult();
if(++idToPlay == maxNumberPlayers) idToPlay = 0;
dice.round = 0;
$( 'span[id$="-action"]').html('');
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random()*6)+1);
if (this.diceValue === 1) {
this.roll = 0;
this.round = 0
} else {
this.roll = this.diceValue;
this.round += this.roll;
}
}
Player.prototype.calcScore = function(isHoldButton = false) {
dice.rollDice();
if (dice.roll === 0) {
dice.round = 0;
switchPlayers();
} else {
this.round += dice.roll;
displayResult();
}
}
function displayResult(){
let id = '#p' + idToPlay;
$(id + '-name').html(players[idToPlay].name);
$(id + '-total').html(players[idToPlay].score);
$(id + '-roll').html(dice.roll);
$(id + '-round').html(dice.round);
$(id + '-dice').html(dice.diceValue);
}
//ui logic
$(document).ready(function() {
initGame();
$("button.btn-roll").click(function() {
players[idToPlay].calcScore();
});
$("button.btn-hold").click(function() {
players[idToPlay].score += dice.round;
switchPlayers();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<p>Rule: If you roll a 1, you will receive 0 roll points for the round and it will be the other player's turn.
</p>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name"><span id="p0-name">Player 1</span><span> </span><span id="p0-action"></span></div>
<div class="player0-score">
<p>Dice points:<span id="p0-dice"></span>
<span> </span>Roll points:<span id="p0-roll"></span>
<span> </span>Round points:<span id="p0-round"></span>
<span> </span>total:<span id="p0-total"></span>
</p>
</div>
</div>
<div class="player-1-panel">
<div class="player-name"><span id="p1-name">Player 1</span><span> </span><span id="p1-action"></span></div>
<div class="player1-score">
<p>Dice points:<span id="p1-dice"></span>
<span> </span>Roll points:<span id="p1-roll"></span>
<span> </span>Round points:<span id="p1-round"></span>
<span> </span>total:<span id="p1-total"></span>
</p>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>

Javascript Help - Timer (Not Counting Up) and Alert Box (Not Showing Up)

I am new to JavaScript and HTML but am slowly getting HTML but JavaScript I am struggling with. I am stuck on a problem that is having me have a counter start when I click the Start Quiz button. I am also having a problem with an Alert Box showing up when I click the Submit Answers button. I am not looking for someone to give me the answer but some guidance would be helpful.
<head>
<meta charset="UTF-8" />
<title>Trivia Quiz: Movies</title>
<script src="modernizr-1.5.js" type="text/javascript" ></script>
<link href="quiz.css" rel="stylesheet" type="text/css" />
<script src="functions.js" type="text/javascript" ></script>
<script type="text/javascript">
var seconds = "0";
var clockID;
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementByID('quizclock')value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
window.alert("You have" + correctAns + "correct of 5 in" + timer + "seconds");
}
</script>
</head>
<body onload="resetQuiz()">
<form id="quiz" name="quiz" action="">
<header>
<img src="tlogo.png" alt="Online Trivia" />
<nav class="horizontal">
<ul>
<li>Top Scores</li>
<li>Submit a Quiz</li>
<li>Quiz Bowl</li>
<li>Your Account</li>
</ul>
</nav>
</header>
<nav class="vertical">
<h1>Categories</h1>
<ul>
<li>Arts</li>
<li>Books</li>
<li>Culture</li>
<li>Geography</li>
<li>History</li>
<li>Movies</li>
<li>Music</li>
<li>People</li>
<li>Random</li>
<li>Science</li>
<li>Sports</li>
<li>Television</li>
</ul>
</nav>
<section id="main">
<h1>Movie Trivia</h1>
<p>
All of our trivia quizzes are scored on the number of correct
answers and the time required to submit those answers.
</p>
<p>
To start the quiz, click the <b>Start Quiz</b> button below,
which will reveal the first page of quiz questions and start
the timer. When you have completed the questions, click
the <b>Submit Answers</b> button on the quiz form.
</p>
<aside>
<input name="quizclock" id="quizclock" value="0" />
<input id="start" type="button" value="Start Quiz" onclick="startClock()" />
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>
</aside>
</section>
</form>
</body>
The code that is provided is partial and I believe that is the only part of the code that is needed for the question. Thanks.
Reset Function as requested:
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++) document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
You have two errors.
1. document.getElementByID('sth') should be document.getElementById('sth').
Notice the lowercase d at the end of Id.
2. You should put a . before value like this:
document.getElementById('quizclock').value = seconds;
This is all assuming that you have implemented startQuiz(), resetQuiz() and showQuiz() and they are working correctly.
Hope Helps;
Try to run the code snippet!
var Quiz = (function($) {
var updateView = function(timeElapsed) {
$('#result').html(timeElapsed);
};
function Quiz() {
updateView(this.timing);
}
Quiz.prototype.timing = 0;
Quiz.prototype.start = function() {
var self = this;
if(self._isCounting) {
return;
}
return this._interval = (function() {
self._isCounting = true;
var interval = window.setInterval(function() {
self.timing += 1;
updateView(self.timing);
}, 1000);
return interval;
})();
};
Quiz.prototype.stop = function() {
window.clearInterval(this._interval);
this._isCounting = false;
return this;
};
Quiz.factory = function() {
return new Quiz();
};
return Quiz;
})(window.jQuery);
window.jQuery(document).ready(function($) {
var historyQuiz = Quiz.factory();
historyQuiz.start();
var modalIsOpen = false;
$('#stop').click(historyQuiz.stop.bind(historyQuiz));
$('#resume').click(historyQuiz.start.bind(historyQuiz));
$('#submitQuizData').click(function(event) {
historyQuiz.stop();
return $.Deferred().resolve(historyQuiz.timing)
.then(function(val) {
return $('#quizResult').html(val + 's')
})
.then(function(element) { return element.fadeIn(); })
.then(function(element) { modalIsOpen = true; })
});
$('#quizResult').click(function() {
if(modalIsOpen) { modalIsOpen = false; return $('#quizResult').fadeOut(); }
});
});
.quiz-result {
display: none;
text-align: center;
width: 300px;
height: 300px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="stop">STOP QUIZ</button>
<button id="resume">RESUME QUIZ</button>
<button id="submitQuizData">SUBMIT QUIZ DATA</button>
<div id="quizResult" class="quiz-result"></div>

how to use addEventListener to get list of elements?

Can someone help out here? i have this project going on... i want that when the list items in the 'players' array are clicked, they should move to the 'actual-players' list. i want to use an event listener.... below are my codes...
JAVASCRIPT
function init(){
var players = ["Player1", "Player2", "Player3", "Player4",
"Player5"];
var listItems = document.getElementById("first");
for (var i = 0; i < players.length; i++){
var newPlayersList = document.createElement("li");
newPlayersList.ClassName = "list-item";
var listItemsValue = document.createTextNode(players[i]);
newPlayersList.appendChild(listItemsValue);
listItems.appendChild(newPlayersList);
}
//Below is where i write the codes to set the elements of the 'players' array to move to the 'actual-players' list. But it doesn't work!
var players = document.getElementsByClassName("list-item");
for(var i=0; i<players.length; i++){
players[i].addEventListener("click", function(){
var text = this.innerHTML;
var liElement = document.createElement("li");
liElement.ClassName = "test";
var text = document.createTextNode(text);
liElement.appendChild(text);
var lis = document.getElementById("actual-
players").getElementsByTagName("li");
if (lis.length == 4){
alert("Don't let more than four players");
} else {
document.getElementById("actual-
players").appendChild(liElement);
this.remove();
}
});
}
}
window.onload = function(){
init();
};
HTML
<html>
<head>
<title>Table Soccer Teams</title>
<link rel="stylesheet" type="text/css" href="soccer.css" />
<script type="text/javascript" src="table_soccer.js" ></script>
</head>
<body>
<a id="reset" href="javascript:location.reload(true)"
class="btn">Reset</a>
<div id="soccer_field">
<div class="players" onsubmit="return(validateForm ());">
<h2>Possible Players</h2>
<ul id="first"></ul>
<p class="one">Click on names above <br>to select actual
players</p>
</div>
<div class="actual_players">
<h3>Actual Players</h3>
<ul id="actual-players" ></ul>
<p class="two">Click button below to <br>generate Teams</p>
<br>
<a id="generate" href ="#" class="btn">Click here</a>
</div>
</div>
</body>
</html>

Using one function with different variables

Try to create two controllers with a same logic. when I use separate functions for each var it works. But when I try to pass var as parameter it does nothing.
Code here:
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num) {
$scope.num ++;
};
$scope.dist_btn = function(num) {
if ($scope.num > 0) {
$scope.num --;
} else {
$scope.num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1)">-</button>
<button ng-click="add_btn(Score2">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2)">-</button>
</div>
</div>
You can use this logic without useing any array, you used $scope.num but it creates a new variable on the scope so fails. this would work properly
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num,from) {
num ++;
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
$scope.dist_btn = function(num,from ) {
if (num > 0) {
num --;
} else {
num = 0;
}
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1,1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1,1)">-</button>
<button ng-click="add_btn(Score2,2)">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2,2)">-</button>
</div>
</div>
Simple and dirty solution :)
There could be something better
function Ctrl($scope) {
$scope.Score = [0, 0];
$scope.add_btn = function(num) {
$scope.Score[num]++;
};
$scope.dist_btn = function(num) {
if ($scope.Score[num] > 0) {
$scope.Score[num]--;
} else {
num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(0)">+</button>
<input type="text" value="{{Score[0]}}">
<button ng-click="dist_btn(0)">-</button>
<button ng-click="add_btn(1)">+</button>
<input type="text" value="{{Score[1]}}">
<button ng-click="dist_btn(1)">-</button>
</div>
</div>
$scope.num // find num inside #scope
$scope[num] // find the member inside scope variable with the value of num (Score1 in your case)
also send the parameter from the element like this:
<button ng-click="add_btn('Score1')">+</button>
and instead num please refactor to id or something.. in short:
$scope.add_btn = function(id)
{
$scope[id]++;
};

Categories