Javascript showing wrong results - javascript

HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript is :
Whenever this code is loaded :
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
Whenever this code is loaded in a browser, the span showing the result for player 1 is showing one directly without clicking on player 1 button. i'm not sure what is wrong with the event listener im using.

The event is click instead of onclick
The event listener should be a reference to the function itself, not the result of a function call (which increments the score by 1)
Inside the function, you can access the button with this:
The code could look like this:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);

Use click event not onclick
You pass result of function not instead reference to function
If you need pass parameters to event handler - you can use bind:
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
[ https://jsfiddle.net/6vw8ay3x/ ]

You have a couple problems there. First, when calling the addEventListener function, you need to specify just "click", not "onclick". Secondly, when you pass the function to addEventListener, you just want it to be a reference to the function not an actual function call. The following changes will net you the result you are seeking.
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
But since you want to be able to use the same function for multiple players, then I would suggest adding the "onclick" handler to the HTML which will allow you to pass the element you want to increment. Then your HTML code would look like this:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
and your javascript would be:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}

window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}

Related

Function does not change a var as I thought it would

I am trying to make a simple function that increases the number value of one variable by the value of another variable.
( a = 2 ) ( b = 5 ) ( a = a + b )
document.write(a) gives ( 2 ), which is ( a ) but unchanged. I expected to get ( 7 ). What am I doing wrong?
var a = 2;
var b = 5;
function add() {
a = a + b;
}
document.write(a)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) write before add function calls so no change. You need to update the element in the inside function
You need to add an HTML element to show your data and use innerHTML to set it
var a = 2;
var b = 5;
function add() {
a = a + b;
// instead of document.write, find the element that you want to hold your element
// and set it's inner html to your value
//this will update the DOM
document.getElementById("myHeader").innerHTML = a;
}
<input type="button" value="add" onclick="add()">
<!-- add an element to hold your result -->
<h1 id="myHeader">Hello World!</h1>
Make the neccsary changes in the code,
You have to write the document.write() at the time you make the function call .
In your case : You wrote it in body so whenever the page load at that time it takes the inital value of a and when you make the function call , the value of a get increased but not print .
<!DOCTYPE html>
<html>
<head>
<script>
var a = 2;
var b = 5;
function add() {
a = a + b;
document.write(a)
}
</script>
</head>
<body>
<div>
<script></script>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) function call is only run the first time the page loads. when you click the button, that only runs the add() function but does not rerun document.write(a)

How to remove previous eventListener?

var keyPress = function(){
x = document.querySelector(".textt");
x.addEventListener("keyup", function(event){
var keyp = document.querySelector(".textt").value;
console.log(event);
document.getElementById("submit").addEventListener("click", function(){
create(event);
x.value = "";
})
})
}
var create = function(event){
var out = document.querySelector(".output");
var displa = document.createElement('li');
displa.textContent = "The key Code for " + event.key + " is: " + event.keyCode;
out.appendChild(displa);
}
function clearAll(){
location.reload();
}
<!DOCTYPE html>
<html>
<head>
<title> ASCI </title>
</head>
<body>
<p> Enter any Character </p>
<form>
<input class="textt" type="text" id = "inp" onkeypress="keyPress()">
</form>
<button id="tt" onclick="clearAll()">Clear</button>
<button id="submit">Submit</button>
<ul class="output">
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
**Output1: First time when I press a key I'm able to get keycode
The key Code for a is: 65
**
**Output2: Second time I press key I'm able to get keycodes but it also gives me output for previous key as well as the 2 times the for the new key pressed
The key Code for a is: 65
The key Code for a is: 65
The key Code for b is: 66
The key Code for b is: 66
**
Can someone help me to resolve this? I only want the output for the new key pressed not previous ones's.
Use
x.onkeyup = null;
Before the x.addEventListener line. It'll clear the previous event listener before assigning the new one.
the previous answer is correct, only if the event handlers were assigned using element.event = function. For the addEventListener method, removeEventListener is required to deal with these.
Usage:
element.removeEventListener("the event", the function you want to remove);
But in your case, you used an anonymous function for the handler. It should be like this.
function myFunc(){
console.log("hello world");
}
element.addEventListener("click", myFunc);
element.removeEventListener("click", myFunc);
// This does not work
myFunc = function(){...};
// This also does not work
element.addEventListener("click", function(){console.log("hello world");});
element.removeEventListener("click", function(){console.log("hello world");});

element is getting variable without declared

I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>

jQuery : Using buttons generated by a plugin to interact with

i'm beginner in jQuery Plugin's coding.
I've coded a plugin to generate a Gantt's calendar but i can't succeed with interacting with it.
The code is too long to be posted so i've coded a sample of what a need in kind of interaction.
Here is a sample code that generate a counter and two buttons to increase or decrease the value of the counter.
So the question is : How can i make the button increase / decrease the counter and of course refresh display.
Thanks,
[EDIT]
I explain again what i want to do :
- The buttons are generated by the plugin.
- When they are clicked, they increase/decrease the value and refresh display
- I dont want an external action binding.
- The plugin must be standalone
[/EDIT]
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<link rel="stylesheet" href="/styles/jquery-ui.css" type="text/css">
<script src="/scripts/jquery.js"></script>
<script src="/scripts/jquery-ui.js"></script>
<script>
(function($){
$.fn.mySample = function() {
var _myCount = 0;
this.initialize = function ()
{
this.html('<input type="button" value="--">Count : ' + _myCount + '<input type="button" value="++">');
}
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Sorry for my first answer :)
So here is your mySample plugin working as a standalone
http://jsfiddle.net/P4p3m/2/
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<script src="jquery-1.11.0.min.js"></script>
<script>
(function($){
$.fn.mySample = function() {
this._counter = 0; // Your counter
this.initialize = function (config)
{
// Get the context of the outside
var context = this;
// Init the -- button
var inputMinus = document.createElement("input");
inputMinus.type = "button";
inputMinus.value = "--";
$(inputMinus).click(function(){
context.updateCounter(-1);
});
this.append(inputMinus);
// Init the display
var spanDisplay = document.createElement("span");
context.spanDisplay = spanDisplay;
$(spanDisplay).text(context._counter);
this.append(spanDisplay);
// Init the ++ button
var inputPlus = document.createElement("input");
inputPlus.type = "button";
inputPlus.value = "++";
$(inputPlus).click(function(){
context.updateCounter(+1);
});
this.append(inputPlus);
}
// Updating the counter value and the display
this.updateCounter = function(nbr){
this._counter += nbr;
$(this.spanDisplay).html(this._counter);
};
// Start the plugin
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
I modified your code to add id's to better identify the buttons and a span to identify where we want to modify the count:
Here's the updated code to reflect your comments, along with the code working in a fiddle: http://jsfiddle.net/XMgz4/
(function ($) {
$.fn.mySample = function () {
var _myCount = 0;
var inputStr = '<input id="decButton" type="button" value="--">'
+ 'Count : <span id="count">' + _myCount
+ '</span><input id="incButton" type="button" value="++">';
this.html(inputStr);
this.find("#decButton").on("click", function() {
_myCount --;
$("#count").text(_myCount);
});
this.find("#incButton").on("click", function() {
_myCount ++;
$("#count").text(_myCount);
});
}
})(jQuery);
You will need to put the Count : ' + _myCount + ' inside an element.. like this:
'Count : <div id="result">' + _myCount + '</div>'
After that you will create a function to get the value of result.. like this $('#result').html()
and increase or decrease the value using onclick event of your inputs... (You must to add class or id for your inputs...)
I will suppose that the id is btnDecrease and btnIncrease... You will need to do something like this:
$('#btnDecrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) - 1);
});
and
$('#btnIncrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) + 1);
});
Hope it helps

Bug displaying a div element when a user clicks on a button

I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno
Perhaps because the function is called traverse() and you're calling traverse_tree()?
Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));

Categories