Calling Javascript from a html form

后端 未结 6 417
眼角桃花
眼角桃花 2021-01-30 06:18

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

相关标签:
6条回答
  • 2021-01-30 06:54

    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>
    
    0 讨论(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>
    
    0 讨论(0)
  • 2021-01-30 06:58

    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)"> 
    
    0 讨论(0)
  • 2021-01-30 07:02

    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
    }
    
    0 讨论(0)
  • 2021-01-30 07:03

    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>
    
    0 讨论(0)
  • 2021-01-30 07:09

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

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

    0 讨论(0)
提交回复
热议问题