简体   繁体   English

从 html 表单调用 Javascript

[英]Calling Javascript from a html form

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.我试图避免使用eventListener ,而只是在单击提交按钮时调用handleClick onsubmit

Absolutely nothing happens with the code I have.我拥有的代码绝对没有任何反应。

Why is handleClick not being called?为什么没有调用handleClick

<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>

You can either use javascript url form with您可以使用 javascript url 表单

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

Or use onSubmit event handler或者使用 onSubmit 事件处理程序

<form onSubmit="return handleClick()">

In the later form, if you return false from the handleClick it will prevent the normal submision procedure.在后一种形式中,如果您从 handleClick 返回 false,它将阻止正常的提交过程。 Return true if you want the browser to follow normal submision procedure.如果您希望浏览器遵循正常的提交程序,则返回 true。

Your onSubmit event handler in the button also fails because of the Javascript: part由于Javascript:部分,您在按钮中的 onSubmit 事件处理程序也失败了

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>

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.因此,您在 getradiobuttonvalue 函数中的单选按钮未定义并引发错误。

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:编辑要从单选按钮中获取值,请获取JQuery库,然后使用以下命令:

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

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:编辑 2由于希望重新发明轮子,这里是非 Jquery 代码:

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:编辑 3这是你的作业:

      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.请注意以下内容,我已将函数调用移至表单的“onSubmit”事件。 An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button.另一种方法是将您的提交按钮更改为标准按钮,并将其放入按钮的 OnClick 事件中。 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.我还删除了函数名称前面不需要的“JavaScript”,并在函数输出的值上添加了显式 RETURN。

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.结构是: document.[THE FORM NAME].[THE CONTROL NAME]来处理事情。 Since you renamed your from aye, you had to change the document.myform.由于您从 aye 重命名了您的文件,因此您必须更改 document.myform。 to document.aye.到文档。是的。 Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing .此外, document.aye["whichThing"]在这种情况下是错误的,因为它需要是document.aye.whichThing

The final bit, was I commented out the event.preventDefault();最后一点,是我注释掉了event.preventDefault(); . . that line was not needed for this sample.该样本不需要该行。

EDIT 4 Just to be clear.编辑 4只是为了清楚。 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. document.aye["whichThing"]将为您提供对所选值的直接访问,但document.aye.whichThing 可让您访问需要检查的单选按钮集合。 Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing .由于您正在使用“getRadioButtonValue(object)”函数来遍历集合,因此您需要使用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
}

Pretty example by Miquel (#32) should be refilled:应该补充 Miquel (#32) 的漂亮例子:

<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)"> 

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.您对使用document.myform['whichThing']的建议有点过于字面化了。 Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].您的表单名为“aye”,因此访问 whichThing 单选按钮的代码应使用该名称:`document.aye['whichThing']。

  2. There's no such thing as an action attribute for the <input> tag. <input>标签没有action属性这样的东西。 Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>改用onclick<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.在浏览器中获取和取消 Event 对象是一个非常复杂的过程。 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. IE 和 Firefox 处理这些事情的方式非常不同,所以一个简单的event.preventDefault()将不起作用……事实上,事件变量甚至可能不会被定义,因为这是来自标签的 onclick 处理程序。 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).在这种情况下,作为一个简单的解决方法,在 onclick 标记中使用return false ,如上面的数字 2 中所示(或按照 stephen 的建议从函数返回 false)。

  4. Because of #3, get rid of everything not the alert statement in your handler.由于#3,去掉处理程序中除警报语句以外的所有内容。

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>

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).在您的代码中,一切似乎都很完美,除了 handleClick() 无法正常工作,因为此函数在其函数调用中缺少参数(但其中的函数定义有一个参数,导致函数不匹配)。

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.它演示了在 html 文件中使用 JavaScript 函数(调用)并解决了您面临的问题。

<!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>

Remove javascript: from onclick=".. , onsubmit=".. declarations删除javascript: from onclick=".. , onsubmit="..声明

javascript: prefix is used only in href="" or similar attributes (not events related) javascript:前缀仅用于href=""或类似属性(与事件无关)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM