Jump to content

JS: increment & decrement


tinfanide
 Share

Recommended Posts

<script>var x = 0;function add(){	var num = document.getElementById('num');	num.value = x;	x=x+1;		}function minus(){	num.value = x;	x=x-1;	}	</script></head><body><input id="num" type="text" /><input onclick="add()" type="button" value="+1" /><input onclick="minus()" type="button" value="-1" /></body></html>

I found that every time I decrement/increment the number after decrementing/incrementing that, the number will increase/decrease by 1 before it does according which button (+1/-1) is pressed.For example,Press +1, it + 1Press -1, it still +1Press -1, it then returns to be proper: it -1Vice versa.Is there anything wrong with my functions?

Link to comment
Share on other sites

wouldn't it make since to to write the value of x back to the input after you've worked on it? perhaps you are meaning to do something like this:

<html><body><script type="text/javascript">var x = 0;var inputElement = {};function add(){  var currentValue = inputElement.value;  x = currentValue + 1;  writeToInput();};function minus(){  var currentValue = inputElement.value;  x = currentValue - 1;  writeToInput();}function writeToInput(){  inputElement.value = x;};function init(){  inputElement = document.getElementById('num');};window.onload = init;  //using this so we can get a reference to the input element _after_ the page has loaded</script></head><body><input id="num" type="text" /><input onclick="add()" type="button" value="+1" /><input onclick="minus()" type="button" value="-1" /></body></html>

edit: it's just a baseline, using a couple globals, but could be refactored down even more, but this is just a lesson after all... :)

Edited by thescientist
Link to comment
Share on other sites

You are setting the value before you increment/decrement it. So the input will always display the last value of x. Move the line that assigns x to the value after the line that increments/decrements x.Oh and num will be undefined in your second function.EDIT:@scientist:Oh get all fancy would ya...:)

Edited by ShadowMage
Link to comment
Share on other sites

You are setting the value before you increment/decrement it. So the input will always display the last value of x. Move the line that assigns x to the value after the line that increments/decrements x.Oh and num will be undefined in your second function.EDIT:@scientist:Oh get all fancy would ya...:)
:)
*tsk-tsk* - is somebody jealous ? :P xDjust to confirm my understanding; window.onload = init;onload here is a property (wait, method ?) of the window Object.whereas on the other thread; window.showcase = <<DOM element>>;showcase is being declared as a variable to the DOM element window, right ? Edited by edGetItTypee
Link to comment
Share on other sites

wouldn't it make since to to write the value of x back to the input after you've worked on it? perhaps you are meaning to do something like this:
<html><body><script type="text/javascript">var x = 0;var inputElement = {};function add(){  var currentValue = inputElement.value;  x = currentValue + 1;  writeToInput();};function minus(){  var currentValue = inputElement.value;  x = currentValue - 1;  writeToInput();}function writeToInput(){  inputElement.value = x;};function init(){  inputElement = document.getElementById('num');};window.onload = init;  //using this so we can get a reference to the input element _after_ the page has loaded</script></head><body><input id="num" type="text" /><input onclick="add()" type="button" value="+1" /><input onclick="minus()" type="button" value="-1" /></body></html>

edit: it's just a baseline, using a couple globals, but could be refactored down even more, but this is just a lesson after all... :)

Sorry, I've just tested it.It fixed the problem I mentioned.But the function add() has got another problem. It just adds 1 after the number:111111Why was that?
Link to comment
Share on other sites

<script>var x = 0;function add(){	var num = document.getElementById('num');	num.value = x;	x=x+1;		}function minus(){	num.value = x;	x=x-1;	}	</script>

<script>window.onload = function(){	window.num = document.getElementById('num');}var x = 0;function add(){	x=x+1;	num.value = x;		}function minus(){	x=x-1;	num.value = x;	}</script>

I've just played around with the order of the codes and found thatif I put num.value = x after x=x+1 or x=x-1, I get what I wanted in the previous post.I don't know why but I reckon it might be considered by JS that after the addition or the subtraction, num.value is assigned to be x. Before, if num.value is written before... I don't know what I was gonna say...But consider this:Now I use index. But when I put the value after y=y+1 or y=y-1, the first will be undefined.Please try to test it on your browser. There are something more than words can say... quite weird...For the reserve functionI wanna make it reserve so that as far as the index is minused into negatives, it still reserves the order of the cat names.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JS: Incremental/Decremental Counter</title><script>var y = 0;function idxloop(){	var n = document.getElementById('n');	var cats = ["Dino", "Jarque", "Marble", "Pineapple"];	y++;	n.value = cats[y];	if(y >= cats.length)		{y = 0;}	}function idxloopreverse(){	var n = document.getElementById('n');	var cats = ["Dino", "Jarque", "Marble", "Pineapple"];		y--;	n.value = cats[y];	if(y < 0)		{y = 0;}	}</script></head><body><input id="n" type="text" /><input onclick="idxloop()" type="button" value="Forward" /><input onclick="idxloopreverse()" type="button" value="Backward" /></body></html>

Link to comment
Share on other sites

Sorry, I've just tested it.It fixed the problem I mentioned.But the function add() has got another problem. It just adds 1 after the number:111111Why was that?
The plus operator is an overloaded operator, meaning it serves multiple purposes. It concatenates strings and it adds numbers.In this case, it is concatenating strings. Any time you retrieve a value from a form input it will be a string. Always. You have to explicitly convert it to a number like this:var currentValue = Number(inputElement.value);
Now I use index. But when I put the value after y=y+1 or y=y-1, the first will be undefined.Please try to test it on your browser. There are something more than words can say... quite weird...
You're trying to set the value to an element in the array that doesn't exist. If y is 0 and you click the minus button, you are trying to set the value of the input to cats[-1], which doesn't exist. Same thing if y is 3 and you click the plus button. cats[4] does not exist. You have to move the value assignment after you do your checking of the y value, like this:y++;if(y >= cats.length) {y = 0;}n.value = cats[y];Also, are you sure you wanted to go back to the first element if you click plus when the last element is active? You can just prevent it from advancing by setting y to cats.length-1
For the reserve functionI wanna make it reserve so that as far as the index is minused into negatives, it still reserves the order of the cat names.
Not really sure I understand...
Link to comment
Share on other sites

Not really sure I understand...
I mean when I press "backward"It does something like 3 -> 2 -> 1 -> 0 -> 3 -> 2 -> 1 -> 0 ...But later on I fixed it and it's something like:
function idxloopreverse(){	y--;	if(y < 0)		{y = y + cats.length;}	n.value = cats[y];	}

I used y = y + cats.length

Link to comment
Share on other sites

just to confirm my understanding; window.onload = init;onload here is a property (wait, method ?) of the window Object.whereas on the other thread; window.showcase = <<DOM element>>;showcase is being declared as a variable to the DOM element window, right ?
yes, onload is method/function of the window object. I typically call functions that are part of an object or class methods. It's kind of interchangeable however.in the second example, yes you could call it a variable, but in my eyes, since window is an object, in this case I would say you are setting a property of the window object, in this case one that you made, equal to an object. I guess IMO, there are minor distinctions in terminology when dealing with an object, but I'm sure it's all really one half dozen to the other.
Link to comment
Share on other sites

Just so we're clear on this:In a browser, window is the global namespace. Any variable or function declared globally is by definition a property or method of the window object. Therefore:window.showcase = something;is identical toshowcase = something;just aswindow.alert("hello");is identical toalert("hello");

Link to comment
Share on other sites

Just so we're clear on this:In a browser, window is the global namespace. Any variable or function declared globally is by definition a property or method of the window object. Therefore:......
i see, okay.just to clarify which other thread i was referring to;and now, having read the one on this thread again, window.onload here is actually a user-defined function and not the JS Event ?
Link to comment
Share on other sites

Correct. Think of window.onload as a "location" where you can store a function that executes when the window's load event fires. Standards-compliant browsers treat event handlers differently from other functions/methods. Specifically, the browser executes them automatically, whenever the correct event fires. Also, the browser passes the event handler an event object corresponding to the event that was fired. No other functions work in this way.Event handling is an aspect of JavaScript where developers tend to get sloppy when we talk to each other, but mostly everyone figures out what we're talking about anyway. Asking about it is okay because it takes a while for it all to sink in. Mostly, you just have to experiment a lot.

Edited by Deirdre's Dad
Link to comment
Share on other sites

window.onload here is actually a user-defined function and not the JS Event ?
what I have set the value of onload to is user-defined. onload itself is an event. Edited by thescientist
Link to comment
Share on other sites

WOW!! where else can you get a ratio of three teachers to ONE student !!w3schools : BEST. SCHOOL. EVER. !!!

windows.onload is actually a method, which is overridden when you make it reference a new method.
what I have set to the value of onload to is user-defined. onload itself is an event.
sorry, one more time so i truly grasp this absolutely correctly.onload is an event, and a built-in method of the DOM element 'window', which in the above scenario by 'thescientist' has been set by the user.
Link to comment
Share on other sites

yes, that sounds right. just as long as you know onload is always there, and that it's just a matter of wether you make use of it or not, like any other event handler. The most common way to do this is as I have done, which is to create a custom function and assign a reference to that function as the value of the event handler. Better practice though is to use event listeners, i.e. addEventListener.https://developer.mozilla.org/en/DOM/elemen...ddEventListener

Link to comment
Share on other sites

yes, that sounds right. just as long as you know onload is always there, and that it's just a matter of wether you make use of it or not, like any other event handler. The most common way to do this is as I have done, which is to create a custom function and assign a reference to that function as the value of the event handler. Better practice though is to use event listeners, i.e. addEventListener.https://developer.mozilla.org/en/DOM/elemen...ddEventListener
I don't know that I would call it "better" practice. That might be the way the standards recommend, but with the #$*! that IE is doing, I don't think you can call it "better" practice. IE 9 makes it a little more acceptable.I have never had any problems using the "old" way: elem.onclick = func;No problems referencing this. this is always the element firing the event. It works in every browser. The only "advantage" to addEventListener is the ability to attach multiple listeners. But that's just as easy to do using anonymous functions:
elem.onclick = function() {   func1();   func2();}

Long story short, I see no benefit to using the "standard" way in this case.

Link to comment
Share on other sites

yes, that sounds right. just as long as you know onload is always there, and that it's just a matter of wether you make use of it or not, like any other event handler. The most common way to do this is as I have done, which is to create a custom function and assign a reference to that function as the value of the event handler. Better practice though is to use event listeners, i.e. addEventListener.https://developer.mozilla.org/en/DOM/elemen...ddEventListener
I don't know that I would call it "better" practice. That might be the way the standards recommend, but with the #$*! that IE is doing, I don't think you can call it "better" practice. IE 9 makes it a little more acceptable.I have never had any problems using the "old" way: elem.onclick = func;No problems referencing this. this is always the element firing the event. It works in every browser. The only "advantage" to addEventListener is the ability to attach multiple listeners. But that's just as easy to do using anonymous functions:
elem.onclick = function() {   func1();   func2();}

Long story short, I see no benefit to using the "standard" way in this case.

hmm, interesting - using an element's standard(built-in) method, and then assigning multiple functions to it !!food for thought...this is getting into "advanced territory" with the nuances of various approaches to a single objective.thanks as ever, guys.P.S. is addEventListener() a standard method acceptable to all browsers ?(it seems to me, the more advanced a 'language' gets, with "new & improved special bells & whistles" for programming efficiency, the more variety gets introduced causing potential incompatibilities.)
Link to comment
Share on other sites

as per the link, if you scroll to the bottom, you will find there needs to be a special exception made for handling IE < 9. But's a feature test similar to that of creating an XMLHttpRequest object.

Link to comment
Share on other sites

as per the link, if you scroll to the bottom, you will find there needs to be a special exception made for handling IE < 9. But's a feature test similar to that of creating an XMLHttpRequest object.
ok thanks, i think MDN Docs is the go-to reference for those who have already graduated W3Schools.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...