views:

1772

answers:

2

Can I attach any event handlers to HTML hidden? Basically want to run a function with a hiiden control value changes.

Thanks All, ~ck in San Diego

+4  A: 

Events are only triggered when the user performs the event in the browser, so if it's <input type="hidden"> or an <input> hidden by CSS, the user won't be able to trigger events to your input.

The only way you would get onchange to work is if you manually trigger onchange in Javascript. A quick example of this:

<form name="f" onsubmit="document.f.h.value='1'; 
    document.f.h.onchange(); return false;">
<input type="hidden" name="h" value="0"
    onchange="alert(document.f.h.value);" />
<input type="submit" />
</form>
jimyi
+1  A: 

I used the following code to try and answer your question.

Using firefox I observed the following:

  1. clicking the button did not fire the onchange handler
  2. editing the textbox manually did fire the onchange handler

Thus, the onchange handler is not going fire when you update the hidden value programatically.

Why not write a setter method for the hidden element and only use that to change the value. The setter method could perform any logic you planned on putting in the onchange handler.

<html>
<head>
    <script type="text/javascript"> 
     function handleClick() {
      var e = document.getElementById('abc');
      e.value = 'dd';
     }

     function handleChange() {
      var e = document.getElementById('abc');
      alert(e.value);
     }
    </script>
</head>
<body>
    <input type="button" onclick="handleClick();" />
    <input id='abc' type="text" value='rr' onchange="handleChange();" />
</body>
</html>
Lawrence Barsanti