onclick event not triggered when onchange triggere

2019-02-18 23:05发布

问题:

i have a funny problem here.

I have a textarea with an onchange event linked to it. Then i have a button linked to an onclick event.

The text being put to the textarea is processed when the onchange event gets triggered on the textarea. This normally happens when i click something outside of the textarea.

What i did was the following:

  1. I typed in a text into the textarea.
  2. Right after typing i click on the button to trigger the onclick event on the button
  3. Nothing happens, but the onchange event on the textarea got triggered when i clicked on the button, but the onclick event on the button itself doesnt get triggered.

Why? I expected to get both onchange and onclick triggered. Is there anything i need to do so the click on the button doesnt get "lost". I realized i have to click twice, because first click causes onchange on textarea, and THEN the second click triggers onclick on the button.

The code below shows an exmaple, just try the code below. Type in a text, then directly click on that button. Only the "textarea" popup will come up.

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

  function processButton()
  {
    alert( 'button');
  }
</script>

回答1:

You need to recheck your assumptions. In your example, alert() interrupts the program flow, breaking handling of onclick. This code (jsfiddle here) demonstrates 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>​

I had a similar problem, but the actual reason that the onclick event was not handled was that the element being clicked, scrolled down as a result of the onchange handler. When the mouse button was released, the element did not receive a mouseup event and the "click" was interrupted.



回答2:

handle onblur event on textarea and onclick event on button



回答3:

try this to add event listener to components

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

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

if Ids are defined then use getElementById().