user1205577
user1205577

Reputation: 2450

HTML form never calls Javascript

I have a set of radio buttons defined in HTML like so:

<input type="radio" name="group" id="rad1" value="rad1" onClick="doStuff(this.id)">Option 1<br>
<input type="radio" name="group" id="rad2" value="rad2" onClick="doStuff(this.id)">Option 2<br>

Just before the </body> tag, I have the following JavaScript behavior defined:

   <script type="text/javascript">
       /*<![CDATA[*/                   
       function doStuff(var id){
           alert("Doing stuff!");
       }
       /*]]>*/
   </script>

When I run the program, the page loads as expected in my browser window and the radio buttons allow me to click them. The doStuff() function, however, is never called (I validated this using breakpoints as well).

I also tried the following just to see if inline made the difference, but it seems the JavaScript is never called at all:

<script type="text/javascript">
       /*<![CDATA[*/   
       alert("JavaScript called!");
       main();
       function main(){
            var group = document.getElementsByName('group');
                for(var i=0; i<group.length; i++){
                    group[i].onclick = function(){
                        doStuff(this.id);
                    };
                }
       }
       /*]]>*/
</script>

My question is, is there something special I need to do using HTML and JavaScript in this context? My question is not whether I should be using inline function calls or whether this is your favorite way to write code.

Upvotes: 1

Views: 59

Answers (1)

McGarnagle
McGarnagle

Reputation: 102723

The function declaration is bad -- there shouldn't be a "var" there before the parameter:

function doStuff (id) {
   alert("Doing stuff!");
}

Upvotes: 3

Related Questions