Link to home
Start Free TrialLog in
Avatar of DanielSKim
DanielSKim

asked on

Raise onChange Event When Value Set By Javascript

Is there anyway to raise the onChange event of a form element when its value is set with some other javascript code? I don't have total control of the design of the page, and there will be times when other code on the page will change the value of an text input.

Basically, using the example below, I'd like input1OnChange() to run when setInput1Val() is executed.


<form name="form_name" action="" method="post">
      <input name="input1" value="" type="text" onchange="input1OnChange()" />
      <input name="button1" value="Click" type="button" onclick="setInput1Val()" />
</form>

<script>
function setInput1Val() {
      document.forms['form_name'].input1.value = 1;
}
function input1OnChange() {
      alert(document.forms['form_name'].input1.value);
}
</script>
Avatar of third
third
Flag of Philippines image

try,

<form name="form_name" action="" method="post">
     <input name="input1" value="" type="text" onchange="input1OnChange()" />
     <input name="button1" value="Click" type="button" onclick="setInput1Val();this.form.input1.onchange();" />
</form>
Avatar of DanielSKim
DanielSKim

ASKER

sorry for not being clearer but the point is that I don't have access to the entire code that is generated on the page. the above was just an example, but i won't necessarily know what function or element event will set the value for the element i want the onchange event to be raised. if i did, i could put it in the setInput1Val function, but I am hoping there is way to raise the event whenever the value is changed.
ok try using a timer approach

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Author: Third Santor</title>
<script>
function setInput1Val() {
     document.forms['form_name'].input1.value = 1;
}
function input1OnChange() {
     alert(document.forms['form_name'].input1.value);
}

var inputVal = '';
function monitor(){
  if(inputVal != document.forms['form_name'].input1.value){
    inputVal = document.forms['form_name'].input1.value; //assign the new value as inputVal
    input1OnChange();
  }
}

window.setInterval("monitor()", 500);
</script>
</head>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" onload="//setTimeout('monitor(document.form_name.input1)', 500);">
<form name="form_name" action="" method="post">
     <input name="input1" value="" type="text" onchange="input1OnChange()" />
     <input name="button1" value="Click" type="button" onclick="setInput1Val();" />
</form>
</body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of third
third
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks for pointing out the onpropertychange event. i'm working in an IE only corporate environment so that's fine.