By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,231 Members | 1,636 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,231 IT Pros & Developers. It's quick & easy.

why doesn't my button click event fire?

P: n/a
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event. But if I
press the button without entering text first, the button click event
does work. What's up?

<html>
<body>
<h3>Events on Buttons and Text Boxes</h3>

<input id="myTextBox1" type="text" onChange="doChange1()" /<br />
<input id="myTextBox2" type="text" onChange="doChange2()" /<br />

<input id="myButton" type="button" onclick="doClick()" value="Click me"
/>

<script type="text/javascript">
function doChange1(e)
{
var val = document.getElementById("myTextBox1").value;
alert("You typed: " + val);
}

function doChange2(e)
{
var val = document.getElementById("myTextBox2").value;
alert("You typed: " + val);
}

function doClick(e)
{
var _num = prompt("Enter a number", "100");
alert("You typed: " + _num); // number converted to string
automatically
}
</script>

</body>
</html>

Nov 16 '06 #1
Share this Question
Share on Google+
17 Replies


P: n/a

Eric wrote:
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event. But if I
press the button without entering text first, the button click event
does work. What's up?

<html>
<body>
<h3>Events on Buttons and Text Boxes</h3>

<input id="myTextBox1" type="text" onChange="doChange1()" /<br />
<input id="myTextBox2" type="text" onChange="doChange2()" /<br />

<input id="myButton" type="button" onclick="doClick()" value="Click me"
/>

<script type="text/javascript">
function doChange1(e)
{
var val = document.getElementById("myTextBox1").value;
alert("You typed: " + val);
}

function doChange2(e)
{
var val = document.getElementById("myTextBox2").value;
alert("You typed: " + val);
}

function doClick(e)
{
var _num = prompt("Enter a number", "100");
alert("You typed: " + _num); // number converted to string
automatically
}
</script>

</body>
</html>
Ok, couple of points here - and I'll try to keep this focused:

1. I don't see any behavior here that's unexpected. I tested your code
on IE and Firefox and the button click handler gets fired every time I
click it.

2. Why do you duplicate the change handler? Much better would be:

<script type="text/javascript">
function doChange(btn)
{
var val = btn.value;
alert("You typed: " + val);

}
</script>

then

<input id="myTextBox1" type="text" onChange="doChange(this)" /<br />
<input id="myTextBox2" type="text" onChange="doChange(this)" /<br />

Of course, in that case, your handler doesn't get an Event object
passed to it. But you weren't using it anyway. Pretty soon you'll
need to learn about Event objects and unobtrusive event handlers, but
that's too involved for this post. Check out
http://www.quirksmode.org/js/introevents.html for an overview.

3. Your script tags should really go inside your head tags. Actually,
your scripts should really go in a separate file. For a simple example
like this it isn't a big deal, but for a larger project it's pretty
important to keep track of your code in this way. Once you start
peppering <scripttags in the body of your HTML you quickly lose the
ability to keep track of what's where.

4. In your onClick handler, you should understand that _num is always a
string (whether it contains digits or not), it's never a number. If
you wanted an actual number you could do math with, you need to call
parseInt(_num).

Nov 16 '06 #2

P: n/a
ASM
Eric a écrit :
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event. But if I
press the button without entering text first, the button click event
does work. What's up?
You have to let time to time :

function doChange2(e)
{
var val = document.getElementById("myTextBox2").value;
setTimeout(function(){alert("You typed: " + val);},200);
}

fine for me
but could need a longer timer than 200 miliseconds
(depends of processor's capacity ?)

--
Stephane Moriaux et son (moins) vieux Mac déjà dépassé
Stephane Moriaux and his (less) old Mac already out of date
Nov 16 '06 #3

P: n/a

ASM wrote:
Eric a écrit :
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event. But if I
press the button without entering text first, the button click event
does work. What's up?

You have to let time to time :

function doChange2(e)
{
var val = document.getElementById("myTextBox2").value;
setTimeout(function(){alert("You typed: " + val);},200);
}
Very good - this fixed it on IE. It seems it did work OK on FireFox
without this but I wasn't able to test it on FireFox earlier.

But why do we need a time delay/timeout here? This doesn't make sense
to me. I could understand a delay if we were executing dynamically
constucted code, or code that wasn't fully downloaded to the browser,
but this is a simple page?

Eric

Nov 17 '06 #4

P: n/a

David Golightly wrote:
Eric wrote:
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event.
1. I don't see any behavior here that's unexpected. I tested your code
on IE and Firefox and the button click handler gets fired every time I
click it.
It didn't work for me on IE6 or IE7 on WinXP SP2, but it did work on
FireFox when I tested it later. I only had a problem if I entered text
before pressing the button. The timeout suggested by the other poster
fixed it, but I really can't see why?
2. Why do you duplicate the change handler? Much better would be:
<input id="myTextBox1" type="text" onChange="doChange(this)" /<br />
<input id="myTextBox2" type="text" onChange="doChange(this)" /<br />
This is indeed better! I didn't know that "this" could be used to pass
the name of the control, but it does make perfect sense that it would.
This could be a big savings in code while making it more maintainable.
Of course, in that case, your handler doesn't get an Event object
passed to it. But you weren't using it anyway. Pretty soon you'll
need to learn about Event objects and unobtrusive event handlers, but
that's too involved for this post. Check out
http://www.quirksmode.org/js/introevents.html for an overview.
Cool site - I may buy that book. He has a clean presentation that is
easy to follow.

Speaking of quirks mode (we weren't really, but I saw it in the URL
above), I've been reading about this but I can't understand how to be
compatible with both old browsers (quirks mode) and new browsers (via
the use of a DOCTYPE) without sprinkling my code with version checks
anyway. If I specify that I'm XHTML complaint, I still have to test for
old browsers and adjust my code accordingly. So is a DOCTYPE really
helping me if I have to use ugly browser testing code anyway?
3. Your script tags should really go inside your head tags. Actually,
your scripts should really go in a separate file. For a simple example
like this it isn't a big deal, but for a larger project it's pretty
important to keep track of your code in this way. Once you start
peppering <scripttags in the body of your HTML you quickly lose the
ability to keep track of what's where.
Thanks for the advice. I understand that script in the head will finish
loading and be available before the UI renders, thereby eliminating
some possible "object expected" errors. And putting it in a separate
file may also allow the browser to cache it.

Right now I'm just making simple test pages so I can learn from it.
I'll do my best to follow the "best practices" in code I deploy.
4. In your onClick handler, you should understand that _num is always a
string (whether it contains digits or not), it's never a number. If
you wanted an actual number you could do math with, you need to call
parseInt(_num).
Thanks for this clarification, also. I'm not used to a typeless
language that really does have types, and I assumed the conversion
would always be automatic. But in my code I wasn't trying to do math on
it, anyway. I guess if I tried to add 1 it would have blown up unless I
had the parseInt.

Eric

Nov 17 '06 #5

P: n/a
Lee
Eric said:
>
I'm new to JavaScript and I wrote this code to play with. Oddly, if I
enter text in a box and then press the button, I only get the onChange
event for the text box and not the button's onclick event. But if I
press the button without entering text first, the button click event
does work. What's up?
This is why alert() isn't a good way to play with event handlers.

Think about when the onchange event of a text input field happens --
when the mouse is clicked outside the text field or when the input cursor is
tabbed out.

So if you enter text in one of your fields and then click the button, what event
fires first?
--

Nov 17 '06 #6

P: n/a
ASM
Eric a écrit :
>
But why do we need a time delay/timeout here?
Because you can fight the processor and its speed :-)

You leave the text field and change fires before you can reach the
button, your eventual click on this last one doesn't take effect : the
browser is already at work krumbling its mind to display the alert.

During displaying alert box all JS is stopped.

Delay perhaps could be shorter if instead to call an alert you innerHTML
message in some P or span.

What you can also do in your text fields is :
onchange="alert('somenthing changed); doChange1(); myButton.click();"
(don't forget to name your button which has only an id)

--
Stephane Moriaux et son (moins) vieux Mac déjà dépassé
Stephane Moriaux and his (less) old Mac already out of date
Nov 17 '06 #7

P: n/a
ASM
Eric a écrit :
David Golightly wrote:
>Eric wrote:
4. In your onClick handler, you should understand that _num is always a
string (whether it contains digits or not), it's never a number. If
you wanted an actual number you could do math with, you need to call
parseInt(_num).

Thanks for this clarification, also. I'm not used to a typeless
language that really does have types, and I assumed the conversion
would always be automatic. But in my code I wasn't trying to do math on
it, anyway. I guess if I tried to add 1 it would have blown up unless I
had the parseInt.
Say a number in a text field :
var n = document.myForm.myTextField.value; // n is text
n = n*1; // number
n = +n; // number
n = Number(n); // number
n = parseInt(n); // number
n = +n + ''; // text
n = Number(n)+''; // text

document.myForm.myTextField.value++; // increase this value by step of 1
// if value was a number

--
Stephane Moriaux et son (moins) vieux Mac déjà dépassé
Stephane Moriaux and his (less) old Mac already out of date
Nov 17 '06 #8

P: n/a
Are you expecting the JS to respond while the alert box is up? Is that
it? All this business about setting timeouts is absolutely the wrong
way to go about things. The window.alert box is a modal dialog; of
course nothing else will respond on your page while it's up, that's
what a modal dialog does.

Your sequence of events is like this:

1. You type into the box.
2. You click on the button.
3. The box loses focus; the focus has to be released by the box before
it can be applied to the button.
4. The box's onchange event fires
5. The modal alert dialog pops up.
6. Since the onchange event fired before the button onclick event
fired, the modal dialog suppressed the click event. Notice how the
button does not go down in this case.

Firefox saves the suppressed click event for later (after the first
alert is gone), while IE ignores it.

And as another poster said, this is not a problem if you do anything
except show a modal dialog.
Speaking of quirks mode (we weren't really, but I saw it in the URL
above), I've been reading about this but I can't understand how to be
compatible with both old browsers (quirks mode) and new browsers (via
the use of a DOCTYPE) without sprinkling my code with version checks
anyway. If I specify that I'm XHTML complaint, I still have to test for
old browsers and adjust my code accordingly. So is a DOCTYPE really
helping me if I have to use ugly browser testing code anyway?
Well, hehe, this has been the focus of much recent debate on this list.
It really depends on what your target audience is going to be. For
most generic, general-purpose web work, you can safely assume the
browsers you should care about are (in this rough order) IE6, Firefox,
IE7, Safari, Opera 9, and sometimes IE5. Anything else (IE4 or any
version of Netscape, for instance - the modern Netscape uses the
Mozilla engine which in turn is a phoenix reborn of the ancient NS's
ashes) is ancient and for most uses can be considered obsolete. So
most of that "feature testing" code, while good relevant technique for
browser incompatibility, is pretty irrelevant for testing *version* of
browsers. All modern browsers support DOM Level 0 and DOM Level 1, for
example. They're mixed on DOM Level 2 support, so this is where
feature testing comes in.

As for DOCTYPE, yes, you absolutely want to use a DOCTYPE. For most
purposes, you'll want a HTML 4.01 DOCTYPE as this ensures compatibility
with older browsers. If an old browser can't support the DOCTYPE, it
falls back to quirksmode. However, this shouldn't be an issue with any
browsers I listed above. XHTML can be faster and more consistently
rendered, but its full support is patchy and it gets converted into
HTML anyway by most browsers. The real reason DOCTYPEs are important,
though, has more to do with CSS rendering. IE behaves much more
predictably - that is, closer to the W3C standard - when using a valid
DOCTYPE.
I guess if I tried to add 1 it would have blown up unless I
had the parseInt.
Not exactly. In JS the following is true:

'1' + '1' == '1' + 1 == '11'

The + operator is used to concatenate strings, and anything that's not
a string, when added to a string, is automatically converted rather
than throwing an error.

Nov 17 '06 #9

P: n/a

David Golightly wrote:
3. Your script tags should really go inside your head tags.
I just tried this and it also fixed the problem with IE.

Maybe it's a good rule of thumb to put all the script code in the head,
or at least in the body before it's referenced by any UI objects.

Eric

Nov 17 '06 #10

P: n/a
ASM said the following on 11/16/2006 9:11 PM:
Eric a écrit :
>David Golightly wrote:
>>Eric wrote:
4. In your onClick handler, you should understand that _num is always a
string (whether it contains digits or not), it's never a number. If
you wanted an actual number you could do math with, you need to call
parseInt(_num).

Thanks for this clarification, also. I'm not used to a typeless
language that really does have types, and I assumed the conversion
would always be automatic. But in my code I wasn't trying to do math on
it, anyway. I guess if I tried to add 1 it would have blown up unless I
had the parseInt.

Say a number in a text field :
var n = document.myForm.myTextField.value; // n is text
n = n*1; // number
n = +n; // number
n = Number(n); // number
n = parseInt(n); // number
var n = "09";
k = parseInt(n);
alert(k); //0

Don't use parseInt without the Radix unless you know for absolute
certainty that it doesn't contain a leading 0 or 0x

<URL: http://jibbering.com/faq/#FAQ4_12>

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 17 '06 #11

P: n/a
In message <11**********************@h48g2000cwc.googlegroups .com>, Thu,
16 Nov 2006 18:26:26, David Golightly <da******@gmail.comwrites
>
Not exactly. In JS the following is true:

'1' + '1' == '1' + 1 == '11'
Actually, executed as JS, that gives false .
>The + operator is used to concatenate strings, and anything that's not
a string, when added to a string, is automatically converted rather
than throwing an error.
It does, however, convert a Boolean to a Number, and a Function to NaN.

It's a good idea to read the newsgroup and its FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.com/faq/ Old RC FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 17 '06 #12

P: n/a
Dr J R Stockton wrote on 18 nov 2006 in comp.lang.javascript:
>>'1' + '1' == '1' + 1 == '11'

Actually, executed as JS, that gives false .
True, it does.

Try:

alert( '1' + '1' == '1' + 1 == '11' ) // false, because:

alert( ('1' + '1') == ('1' + 1) == '11' ) // false

alert( '1' + ('1' == '1') + (1 == '11') ) // 1truefalse

// btw:

alert( '1' + 1 === '11' ) // true

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Nov 18 '06 #13

P: n/a
In message <Xn*******************@194.109.133.242>, Sat, 18 Nov 2006
10:40:53, Evertjan. <ex**************@interxnl.netwrites
>Try:

alert( '1' + '1' == '1' + 1 == '11' ) // false, because:
I can try it without the alert( or the ) . I just copy from one
window, paste into another, and press "Eval".

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.com/faq/ Old RC FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 18 '06 #14

P: n/a
Dr J R Stockton wrote on 18 nov 2006 in comp.lang.javascript:
I can try it without the alert( or the ) . I just copy from one
window, paste into another, and press "Eval".
I have heard one could press charges, but
how the (d)evil does one press eval?

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Nov 18 '06 #15

P: n/a
<html>
<body>
<textarea id="jscode">
</textarea>
<input type="button"
onclick="alert(eval(document.getElementById('jscod e').value))"
value="Eval" />
</body>
</html>

that's how.

Nov 19 '06 #16

P: n/a
David Golightly wrote on 19 nov 2006 in comp.lang.javascript:
that's how.
That's how what, David?

Please quote on usenet, this is not email.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Nov 19 '06 #17

P: n/a
In message <Xn*******************@194.109.133.242>, Sat, 18 Nov 2006
23:39:31, Evertjan. <ex**************@interxnl.netwrites
>Dr J R Stockton wrote on 18 nov 2006 in comp.lang.javascript:
>I can try it without the alert( or the ) . I just copy from one
window, paste into another, and press "Eval".

I have heard one could press charges, but
how the (d)evil does one press eval?
"Eval", not "eval".

The window to be copied into can be left open, and at least partly
visible on the screen, and "Eval" is written on the first button. One
moves the mouse so that ... .

The window in question is one showing a local copy of my Web page
<URL:http://www.merlyn.demon.co.uk/js-quick.htm>.

To see how it works, get that page, press "Demo" 6N+5 times then press
Eval (NewW only works with some Demo numbers). Demos 2, 3, & 6 are
better examples of normal use.

But read the rest of the page too.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.com/faq/ Old RC FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 19 '06 #18

This discussion thread is closed

Replies have been disabled for this discussion.