Link to home
Start Free TrialLog in
Avatar of ekstern05
ekstern05

asked on

Calling a function from onclick event

Hi,

When I run the following code I get error: "Microsoft JScript runtime error: object expected".  Does anybody know why this happens and how to work around the problem?

Thank you for your help.

Alexandra

<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="GENERATOR" Content="Microsoft Visual Studio">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8">

<script language="javascript">

      function secondCall()      {
        alert("hi");
      }

      
      function firstCall()      {
       document.write("<input type = 'button' value = '2nd click' onclick = 'secondCall()'>");
      }

</script>

</HEAD>


<BODY>
      <input type="button" value="click me" name="myButton" onclick = "firstCall()">
</BODY>
</HTML>
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia 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
And perhaps you are looking for this:

<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="GENERATOR" Content="Microsoft Visual Studio">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8">

<script language="javascript">

     function secondCall()     {
       alert("hi");
     }

     
     function firstCall(theBtn)     {
       theBtn.value = '2nd click';
       theBtn.onclick = function(){secondCall()};
     }

</script>

</HEAD>


<BODY>
<form>
     <input type="button" value="click me" name="myButton" onclick = "firstCall(this)">
</form>
</BODY>
</HTML>

Avatar of ekstern05
ekstern05

ASKER

Thanks Zvonko, that's exactly what I was looking for!

Alexandra
You are welcome.
It looks like the document.write is overwriting the current file, here is a workaround that has the same results.
Hope this helps,
-Tony

<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="GENERATOR" Content="Microsoft Visual Studio">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8">
<SCRIPT language="javascript">
     function Call(){
          if(document.TG.myButton.value=="Click Me"){
               document.TG.myButton.value="2nd Click";}
          else{
               alert("hi");}
}

</SCRIPT>
</HEAD>

<FORM Name="TG">
<BODY>
     <input type="button" value="Click Me" name="myButton" onclick="Call()">
</BODY>
</FORM>
</HTML>