Javascript Form How to - Handle events on related elements








Question

We would like to know how to handle events on related elements.

Answer


<!DOCTYPE html>
<html>
<body>
  <label id="test_label" for="test">Test</label>
  <input type="text" id="test" />
<script type='text/javascript'>
<!-- w ww.  j  a va  2  s .co m-->
    document.getElementById("test_label").onclick = function() {
        console.log("test_label");
    };    
    document.getElementById("test").onclick = function() {
        console.log("test_input");
    };

</script>
</body>
</html>

The code above is rendered as follows: