/    Sign up×
Community /Pin to ProfileBookmark

first function

This script counts characters from a <textarea>. I’m told it’s inline and somehow deficient even though it works. I admit I don’t like the use of the this keyword because I really don’t understand its use. How could I rewrite this script to make it more this century?

[code=html]<html>
<head>
<script language=”javascript” type=”text/javascript”>
var maxAmount = 250;
function textCounter(textField, showCountField) {
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount – textField.value.length;
}
}
</script>
</head>
<body>
<form>
<textarea name=”ta” rows=”6″ style=”width:340px;” onKeyDown=”textCounter(this,document.getElementById(‘ta2’));” onKeyUp=”textCounter(this,document.getElementById(‘ta2’));”></textarea>
<br>
<input readonly id=”ta2″ type=”text” name=”countDisplay” size=”3″ maxlength=”3″ value=”250″> Characters Remaining
</form>
</body>
</html>[/code]

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — First, "this".

It's confusing, because JavaScript is confused about "this". The one area where it's not confusing is when you have an event occuring on an element, such as "ta.onkeydown". The "onkeydown" property contains code. JS will call that code when the key down event occurs over that element. "this" will be a reference to that element. In our example, "this" wll be "ta", your text area. In JS:

this === document.getElementById( 'ta' );

OK? Nothing wrong with "this" as you've used it.

What is wrong is using a string in your assignment to the event properties, "onkeydown" and "onkeyup". When the event occurs, JS sees that it has a string, not code, so JS calls "eval()" to turn the string into code. This is a behavior that is not identical across browsers so I suspect you mean "it works in the browser I'm using". The right way to do it, to avoid cross-browser issues (among other things) is to assign a function:

<i>
</i>var xxx = document.getElementById( 'xxx' );
xxx.onkeydown = keydown;

function keydown() {
textCounter(this,document.getElementById('ta2'));
}


(Please use a more meaningful name than "xxx". I'd also go for something more specific than "ta" and "ta2" - you might have to enhance this code a month or a year from now.)

Test at least in MSIE and Firefox, unless this is personal code. Firefox handles textareas about the same way as Chrome, Opera and Safari. I can't think of any major changes from MSIE 6 through 8.

Good luck!
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — Please show me the the complete script you have in mind. I'm not getting how the changes you're providing will change the html and the function.
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — I just put this up on my site. It's not exactly your issue, but it's very close:

http://www.MartinRinehart.com/frontend-engineering/articles/javascript/javascript-event-triggers.html
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — Thanks for your page. I read it very slowly and found it very understandable and agree with what I think is one of your messages: functions take the ambiguity out of values.

So, to re-write the code starting with the html since that's where all the code comes together with something like this:

[code=html]<form>
<textarea name="ta" rows="6" style="width:340px;"> </textarea>
<br>
<input type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
</form>[/code]


I could code this in PHP though I think javascript will be more efficient. Will you show me how to gain access to the form's keys and values so I can use them in functions?
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — You got thing 1 right. No more "onevent='...'" in the HTML. Good.

Now, in the JS,

var descriptive_name = document.getElementById ...

descriptive_name.onevent = name_of_function;

function name_of_function () {

code that others try to cram into the "onevent = ..." string;

}
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — Uh, another thought. It's not that functions take the ambiguity out of values. The ambiguity is in the process of taking a string, dropping it into the eval() function and then handling the result. That's a lot of steps and those steps live somewhere right in between two standards bodies: ECMA (ECMA 262 is the formal definition of JavaScript) and W3C (the DOM standards body). In glacier climbing that's called a crevasse.
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — I need to limit the <textarea> input to 250 characters. I don't understand how typing in the <textarea> is going to trigger my function.

This is what I have so far for the <script>:

[code=html]<script type="text/javascript">

var maxChar = 251;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');

function calcCharacters2 () {
code that others try to cram into the "onevent = ..." string;
}
</script> [/code]
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — var calcC... // you've got it!

calcCharacters.onkeydown = calcCharacters2; // you need it!

function calcCharacters2... // you've got it!

Good. Uh, names. How about:

var textarea_that_holds_the_characters_to_count = ...

and

function count_the_characters_in_the_ta_textarea() { ...

OK, OK. Those are a bit long. Maybe quite a bit long. On the other hand, the older I get the longer my names get.

You're going strong.

Martin
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — Like this:[code=html]<script type="text/javascript">

var maxChar = 251;
var currentNum = 0;
var textarea_that_holds_the_characters_to_count = document.getElementById('ta');
function count_the_characters_in_the_ta_textarea() {
calcCharacters.onkeydown = calcCharacters2;
}
</script> [/code]


It would help if I knew how the function will be triggered.

By the way, I'm 53 how old are you?

Jim
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — No, no, no! The order is:

var textarea... = document.getElementById ...

textarea.onkeydown = func_name;

function func_name() {

...

}

All JS code comes in two flavors: declarative and imperative. Big words for simple concepts. Declarative code, as the name suggests, declares something. Here are two declarative statements:

var foo;

function bar() { ... }

Imperative code are the statements that actually do something. If the sargeant says "Doubletime, harch!" you go fast. That's an imperative statement. These are code examples:

foo = 2 + 2;

bar(); // execute the "bar" function

JS processes declarative code before it starts running imperative code. So your function definition is processed first. The function is defined and ready to go before, for example, JS goes scurrying around the DOM tree trying to find an element "ta".

When you assign a function to the "onkeydown" property, it sits there, ready and waiting. When the event occurs (element has focus, a physical key is pressed by a user, or my pet Python, Monty, taps the keyboard with his tail) JS looks to see if the "onkeydown" property is defined. If it is defined and its value is a function, JS calls that function. JS will call your function when the event happens. Trust it.

I never write event code first. I always put an alert() into the function:

function count_chars_in_ta() {

alert( "I'm gonna count those chars in ta!" );

}

Get the rest ready to go and then hit a key (or ask Monty to hit a key). When your alert pops up you know you are in business.

And I am older than you. Old enough to have had a sargeant barking "Harch!" at me during Viet Nam. Old enough to have written my first program, in college, before the Beatles released that album about another Sargeant.

Is this your first programming?
Copy linkTweet thisAlerts:
@MartinRinehartJul 08.2011 — By the by, "It would help if I knew how ..." is critically important to me to make my stuff better. It's the thing I thought was obvious that wasn't so obvious. Tomorrow that will be perfectly clear. Thanks!

Martin
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — no joy with this. what am i missing?
[code=html]<script type="text/javascript">

var maxChar = 251;
var currentNum = 0;
var textarea_that_holds_the_characters_to_count = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function count_the_characters_in_the_ta_textarea() {
alert( "I'm gonna count those chars in ta!" );
//calculation of the number of characters in <textarea>;
}
</script>

[/code]


I was in the army 75-84. It was a great experience for me, but glad that I got out when I did. Bought my first computer with my terminal leave money (an IBM pc with two floppies)

I come from a terminal background on the pc. there wasn't anything I couldn't get data to do in a graphically sterile environment. Started scripting last year. know html, css, php, mysql well enough, but no OOP and it shows.
Copy linkTweet thisAlerts:
@niche1authorJul 08.2011 — OK.

played around some more (was missing the id in the <form> which I added and got access to the function.

So, I tested the value of calcCharacters thinking it might be a value, but the alert said calcCharacters is a html object.

How do I need to think about making the calculations in the function. Here's the work so far:
[code=html]<!doctype html>
<html> <head> <title> Counter </title>

</head> <body>
<form id="ta">
<textarea name="ta" rows="6" style="width:340px;"> </textarea>
<br>
<input type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
</form>
<script type="text/javascript">

var maxChar = 251;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function calcCharacters2 () {
alert( "I'm gonna count those chars in ta!" + calcCharacters );
//calculation of the number of characters in <textarea>;
}

</script>

</body> </html>
[/code]
Copy linkTweet thisAlerts:
@MartinRinehartJul 09.2011 — Names are holding you back. Make one of them sound like the name of a textarea, and another one sound like the name of a character counting function.

Then use vertical whitespace (that's geek for "throw in some blank lines"). Make thoughts look like paragraphs. Something like this:

<i>
</i>var maxChar = 251;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');

calcCharacters.onkeydown = calcCharacters2;

function calcCharacters2 () {
alert( "I'm gonna count those chars in ta!" + calcCharacters );
//calculation of the number of characters in &lt;textarea&gt;;
}
Copy linkTweet thisAlerts:
@niche1authorJul 09.2011 — Please show me a little more. I'm not catrching on.
Copy linkTweet thisAlerts:
@MartinRinehartJul 09.2011 — Start with what you had. Fix up the names and add the one line I showed you. It should all work and make sense.
Copy linkTweet thisAlerts:
@niche1authorJul 10.2011 — OK. calcCharacters.value.length counts the number of characters in <textarea> . I have it in a var called x. What's the notation for displaying the value of x in the input box from the <input>?[code=html]<!doctype html>
<html> <head> <title> Counter </title>

</head> <body>
<form >
<textarea id="ta" name="ta" rows="6" style="width:340px;"> </textarea>
<br>
<input id="ta2" type="text" name="countDisplay" size="3" maxlength="3" value="248"> Characters Remaining
</form>
<script type="text/javascript">

var maxChar = 255;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function calcCharacters2 () {
var x = calcCharacters.value.length;
alert( "I'm gonna count those chars in !" + x);
//calculation of the number of characters in <textarea>;
}

</script>

</body> </html>[/code]
Copy linkTweet thisAlerts:
@MartinRinehartJul 10.2011 — OK, I see now that you've missed the basic basics. "." characters are not part of names - they separate objects from objects' properties. "_" characters are part of names.

Give me a chance to get volume I, the JavaScript Language, ready.

I'll get back to you.

Martin
×

Success!

Help @niche1 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...