The onclick event does not fire when onchange fires right before

I have a funny problem.

I have a text box with an onchange event associated with it. Then I have a button associated with the onclick event.

The text that is placed in the text field is processed when the onchange event is fired in the text field. This usually happens when I click something outside the text box.

I have done the following:

  • I entered the text in the text box.
  • Immediately after input, I click the button to trigger the onclick event on the button
  • Nothing happens, but the onchange event in the text field was fired when I clicked the button, but the onclick event on the button itself does not fire.

Why? I expected to get both onchange and onclick. Is there anything I need to do so that a click on a button does not "get lost." I realized that I need to double-click, because the first click calls onchange on textarea, and THEN the second click launches onclick on the button.

The code below is an example, just try the code below. Enter the text, then click on this button. A textarea popup will appear.

<textarea onchange="processText();" name="mytext"></textarea>
<button onclick="processButton();">Hello</button>
<script language="Javascript">
  function processText()
  {
    alert( 'textarea');
  }

  function processButton()
  {
    alert( 'button');
  }
</script>
+3
source share
3 answers

You need to double-check your assumptions. In your example, alert () interrupts the program flow, disrupting onclick processing. This code ( jsfiddle here ) shows that onchange does not interfere with onclick by default:

<textarea onchange="processText();" name="mytext"></textarea>
<button onclick="processButton();">Hello</button>
<div id="clicked"></div>
<div id="changed"></div>
<script language="Javascript">
  function processText()
  {
    document.getElementById('changed').innerHTML = "onchange fired";;
  }

  function processButton()
  {
    document.getElementById('clicked').innerHTML = "onclick fired";
  }
</script>

, , onclick , , , , onchange. , mouseup "click" .

+4

onblur onclick event on button

+1

,

document.getElementsByTagName("textarea")[0].addEventListener("change", function(){
    alert( 'textarea');
});

document.getElementsByTagName("button")[0].addEventListener("click", function(){
    alert( 'button');
});

, getElementById().

0

All Articles