62

I am basing my question and example on Jason's answer in this question

I am trying to avoid using an eventListener, and just to call handleClick onsubmit, when the submit button is clicked.

Absolutely nothing happens with the code I have.

Why is handleClick not being called?

<html>
  <head>
    <script type="text/javascript">
      function getRadioButtonValue(rbutton)
      {
        for (var i = 0; i < rbutton.length; ++i)
        { 
          if (rbutton[i].checked)
            return rbutton[i].value;
        }
        return null;
      }

      function handleClick(event)
      {
        alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
    <form name="myform" onSubmit="JavaScript:handleClick()">
      <input name="Submit"  type="submit" value="Update" onClick="JavaScript:handleClick()"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>
</body>
</html>

edit:

Please do not suggest a framework as a solution.

Here are the relevant changes I have made to the code, which results in the same behavior.

      function handleClick()
      {
        alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye">;
      <input name="Submit"  type="submit" value="Update" action="JavaScript:handleClick()"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joshxtothe4
  • 4,061
  • 10
  • 53
  • 83
  • 1
    none of the methods would work in modern browsers if you don't have the attribute `sandbox="allow-scripts"` for form element. http://www.w3schools.com/Tags/att_iframe_sandbox.asp – Muhammad Umer Jan 10 '15 at 20:09
  • 1
    @MuhammadUmer - AFAIK, the sandbox attributes are *only* needed when you explicitly create an iframe that is a sandbox. If your HTML iframe does not contain the attribute "sandbox", or you don't have an iframe, then how could these restrictions be in effect? – ToolmakerSteve Jul 16 '20 at 00:18
  • 2
    FWIW, the moral of this Q&A is "when it doesn't work, remove stuff from your code, until you find what does work, then work back towards your error". If the alert was simplified to `alert("Favorite weird creature");`, OP would have discovered that worked (the alert appears), and then would have known he had some problem in the syntax of `...getRadioButtonValue(..)`. Successive iterations from what worked towards what doesn't work could have isolated the problem to `this["whichThing"]` isn't returning a value. A much simpler Q&A to have: replace that with `document.aye.whichThing`. Solved. – ToolmakerSteve Jul 16 '20 at 00:32

6 Answers6

77

You can either use javascript url form with

<form action="javascript:handleClick()">

Or use onSubmit event handler

<form onSubmit="return handleClick()">

In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.

Your onSubmit event handler in the button also fails because of the Javascript: part

EDIT: I just tried this code and it works:

<html>
  <head>
    <script type="text/javascript">

      function handleIt() {
        alert("hello");
      }

    </script>
  </head>

<body>
    <form name="myform" action="javascript:handleIt()">
      <input name="Submit"  type="submit" value="Update"/>
    </form>
</body>
</html>
Miquel
  • 4,741
  • 3
  • 20
  • 19
  • 1
    I tried both of these, neither made any difference, no alert was shown regardless of what I tried. –  Mar 25 '09 at 22:06
  • Joshxtothe4 is right... his alert is failing, not primarily because his function isn't being called, nor because it's being called twice due to doubling the javascript event call, but because the this["whichThing"] construct is causing an error. – Jarret Hardie Mar 25 '09 at 23:25
  • Note that using `onSubmit` is the [correct approach](https://stackoverflow.com/a/6909770/6908282) for forms. Also between `onSubmit` & `action`, `onSubmit` will be [triggered first](https://stackoverflow.com/a/29014670/6908282). – Gangula Sep 23 '22 at 05:41
38

In this bit of code:

getRadioButtonValue(this["whichThing"]))

you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

  $('input[name=whichThing]:checked').val() 

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
     if (document.myform.whichThing[i].checked==true) {
         t = t + document.myform.whichThing[i].value;
     }
}

or, basically, modify the original line of code to read thusly:

getRadioButtonValue(document.myform.whichThing))

Edit 3 Here's your homework:

      function handleClick() {
        alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
        //event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye" onSubmit="return handleClick()">
     <input name="Submit"  type="submit" value="Update" />
     Which of the following do you like best?
     <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
     <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
     <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

See the difference in this method:

function handleClick() {
   alert("Direct Access: " + document.aye["whichThing"]);
   alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
   return false; // prevent further bubbling of event
}
AvahW
  • 2,083
  • 3
  • 24
  • 30
Stephen Wrighton
  • 36,783
  • 6
  • 67
  • 86
  • How else would I get the value of a radioButton? –  Mar 25 '09 at 22:05
  • Use getRadioButtonValue(document.myform['whichThing']). I'm glossing over javascript OO a bit here, but "this" is used to refer to an object when a function is part of the object scope. Your example uses top-level functions and no objects. – Jarret Hardie Mar 25 '09 at 23:28
  • Ahh, this is failing as well. Can you give more of an example? –  Mar 26 '09 at 02:32
  • Failing in which way? Make sure you've eliminated the dual calls to handleClick() as Miquel suggests. – Jarret Hardie Mar 26 '09 at 02:43
  • 1
    Please do NOT recommend jquery. I want to understand this without the help of a library. –  Mar 26 '09 at 16:19
  • 1
    If you didn't want JQuery (or some other library) referenced then you should have stated such in the OP. Frankly, it's insane to NOT utilize a library when available – Stephen Wrighton Mar 26 '09 at 16:32
  • I am reposting my code to show what I have now, and that it is not working. –  Mar 26 '09 at 17:26
  • I'd mod you up further stephen if I hadn't already voted for your answer. – Jarret Hardie Mar 26 '09 at 17:52
  • Thanks for all your help. I just wanted to ask why in Jarrets answer is document.aye['whichThing'] used successfully to get the actual value fro favorite weird creature, which is the opposite of this example? –  Mar 27 '09 at 01:31
  • it's just a different way of getting at the data. doc.aye['which'] is saying "get the VALUE of WHICH from the form "document.aye" while doc.aye.which is saying get me the OBJECT(s) of which from the form. – Stephen Wrighton Mar 27 '09 at 03:09
13

Pretty example by Miquel (#32) should be refilled:

<html>
 <head>
  <script type="text/javascript">
   function handleIt(txt) {   // txt == content of form input
    alert("Entered value: " + txt);
   }
  </script>
 </head>
 <body>
 <!-- javascript function in form action must have a parameter. This 
    parameter contains a value of named input -->
  <form name="myform" action="javascript:handleIt(lastname.value)">  
   <input type="text" name="lastname" id="lastname" maxlength="40"> 
   <input name="Submit"  type="submit" value="Update"/>
  </form>
 </body>
</html>

And the form should have:

<form name="myform" action="javascript:handleIt(lastname.value)"> 
empiric
  • 7,825
  • 7
  • 37
  • 48
K.David
  • 151
  • 1
  • 3
3

There are a few things to change in your edited version:

  1. You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].

  2. There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>

  3. Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).

  4. Because of #3, get rid of everything not the alert statement in your handler.

The code should now look like:

function handleClick()
      {
        alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
      }
    </script>
  </head>
<body>
    <form name="aye">
      <input name="Submit"  type="submit" value="Update" onclick="handleClick();return false"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>
Jarret Hardie
  • 95,172
  • 10
  • 132
  • 126
  • Thanks for all your help. I chose Stephens answer as I felt he put a lot more work in, but your answer was also very helpful. Cheers. –  Mar 27 '09 at 01:32
0

Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).

The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.

<!DOCTYPE html>
<html>
<head>
    <title> Semester Results </title>
</head>
<body>
    <h1> Semester Marks </h1> <br> 
    <script type = "text/javascript">
        function checkMarks(total)
        {
            document.write("<h1> Final Result !!! </h1><br>");
            document.write("Total Marks = " + total + "<br><br>");
            var avg = total / 6.0;
            document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
            if(avg >= 90)
                document.write("Grade = A");
            else if(avg >= 80)
                document.write("Grade = B");
            else if(avg >= 70)
                document.write("Grade = C");
            else if(avg >= 60)
                document.write("Grade = D");
            else if(avg >= 50)
                document.write("Grade = Pass");
            else
                document.write("Grade = Fail");
       }
    </script>
    <form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
        Semester 1:  <input type = "text" id = "s1"/> <br><br>
        Semester 2:  <input type = "text" id = "s2"/> <br><br>
        Semester 3:  <input type = "text" id = "s3"/> <br><br>
        Semester 4:  <input type = "text" id = "s4"/> <br><br>
        Semester 5:  <input type = "text" id = "s5"/> <br><br>
        Semester 6:  <input type = "text" id = "s6"/> <br><br><br>
        <input type = "submit" value = "Submit"/>
    </form>
</body>
</html>
VinjaNinja
  • 59
  • 7
-1

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121