why doesn't my button click event fire?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Eric

    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>

  • David Golightly

    #2
    Re: why doesn't my button click event fire?


    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).

    Comment

    • ASM

      #3
      Re: why doesn't my button click event fire?

      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

      Comment

      • Eric

        #4
        Re: why doesn't my button click event fire?


        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

        Comment

        • Eric

          #5
          Re: why doesn't my button click event fire?


          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

          Comment

          • Lee

            #6
            Re: why doesn't my button click event fire?

            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?


            --

            Comment

            • ASM

              #7
              Re: why doesn't my button click event fire?

              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

              Comment

              • ASM

                #8
                Re: why doesn't my button click event fire?

                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

                Comment

                • David Golightly

                  #9
                  Re: why doesn't my button click event fire?

                  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.

                  Comment

                  • Eric

                    #10
                    Re: why doesn't my button click event fire?


                    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

                    Comment

                    • Randy Webb

                      #11
                      Re: why doesn't my button click event fire?

                      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.va lue; // 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.javas cript FAQ - http://jibbering.com/faq
                      Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

                      Comment

                      • Dr J R Stockton

                        #12
                        Re: why doesn't my button click event fire?

                        In message <1163730386.239 736.212880@h48g 2000cwc.googleg roups.com>, Thu,
                        16 Nov 2006 18:26:26, David Golightly <davigoli@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.c om/faq/ Old RC FAQ of news:comp.lang. javascript
                        <URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
                        <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

                        Comment

                        • Evertjan.

                          #13
                          Re: why doesn't my button click event fire?

                          Dr J R Stockton wrote on 18 nov 2006 in comp.lang.javas cript:
                          >>'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)

                          Comment

                          • Dr J R Stockton

                            #14
                            Re: why doesn't my button click event fire?

                            In message <Xns987F76D5764 5eejj99@194.109 .133.242>, Sat, 18 Nov 2006
                            10:40:53, Evertjan. <exjxw.hannivoo rt@interxnl.net writes
                            >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.c om/faq/ Old RC FAQ of news:comp.lang. javascript
                            <URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
                            <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

                            Comment

                            • Evertjan.

                              #15
                              Re: why doesn't my button click event fire?

                              Dr J R Stockton wrote on 18 nov 2006 in comp.lang.javas cript:
                              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)

                              Comment

                              Working...