473,739 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why doesn't my button click event fire?

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="doCha nge1()" /<br />
<input id="myTextBox2 " type="text" onChange="doCha nge2()" /<br />

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

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

function doChange2(e)
{
var val = document.getEle mentById("myTex tBox2").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
17 9676

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="doCha nge1()" /<br />
<input id="myTextBox2 " type="text" onChange="doCha nge2()" /<br />

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

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

function doChange2(e)
{
var val = document.getEle mentById("myTex tBox2").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="doCha nge(this)" /<br />
<input id="myTextBox2 " type="text" onChange="doCha nge(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
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.getEle mentById("myTex tBox2").value;
setTimeout(func tion(){alert("Y ou 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

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.getEle mentById("myTex tBox2").value;
setTimeout(func tion(){alert("Y ou 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

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="doCha nge(this)" /<br />
<input id="myTextBox2 " type="text" onChange="doCha nge(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
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
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
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.va lue; // 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.va lue++; // 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
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

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3008
by: Andrés Giraldo | last post by:
Hi! I'm adding an asp button to a datagrid on the ItemDataBound event, when the user clicks on this button, I basically remove the button and create other 2 buttons... my problem is.. the 2 last buttons doesn't fire his events... what I'm doing wrong? Thanks!
5
6823
by: Carlo Marchesoni | last post by:
From an aspx page (A.aspx) I open another one (B.aspx - for table lookup). When the user selects an entry in B.aspx I would like to force a button's event in A.aspx to be fired. I guess the only way is using javascript - does anybody have a sample for this ? Thanks
2
2354
by: Liqun Xu | last post by:
Hallo NG, I created a Button with Click-Event dynamically: System.Web.UI.WebControls.Button bt_1 = new Button(); bt_1.Click += new EventHandler(bt_1_click); and I implemented the Funktion bt_1_click in which I created a second Button dynamically too. System.Web.UI.WebControls.Button bt_2= new Button();
2
3895
by: Sam Miller | last post by:
Hi, I have a button event that won't fire. I left it on Friday and it worked fine. I came back in on Monday and it won't fire. I tried putting another button and just putting a response.write on its click handler but it won't fire either telling me no button click events will fire. But my calendar control on the same page does fire. In the debugger I put a break point in the calendar event and the button
1
1347
by: John | last post by:
Hi, I have an asp.net page with some validation. On one machine the button click event works fine, whilst on another the button click event does not fire at all Any suggestions welcome! Thanks Mark
24
7693
by: Charles Law | last post by:
When I click a button I don't want the click event to fire. Is this possible? In fact, what I would really like is to be able to intercept the click event, perform some action, and then prevent the click from passing through to the button. Any help or suggestions much appreciated. Charles
2
2393
by: Chu | last post by:
Thanks everyone for taking a moment to read this. I've got a page where I use a LinkButton and I wire up a dynamic event to the button. When the user clicks the button, the event is fired as expected. In the event code for that button, a new LinkButton is added to the page and is wired up to yet a different event, however when clicked, the page is posted back but the event is not triggered. I'm assuming it has something to do with the...
6
3360
by: Jon Paal | last post by:
validation doesn't fire what's missing ????? /////// ---- code -----/////////////////////////// Sub btnSubmit_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) 'Handles btnSubmit.Click If page.isValid then ..... end if
5
5893
by: Tony | last post by:
I am continuing to develop an Access 2007 application which was originally converted from Access 2003. In Access 2003 I was able to disable the Access Close button in the top righthand corner of the screen. I have been unable to find any way to disable this button in Access 2007 and subsequently I have been forced to find ways to detect and handle the situations after the Access Close button has been clicked. I have been largely...
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9479
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9266
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6754
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6054
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3280
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.