duanjiancong4860 2019-05-25 06:13
浏览 504
已采纳

使超链接成为表单提交按钮

I am trying to get a hyperlink element to act as a form submit button. This sort of question has been answered multiple times over the years but, for some reason, I am not able to get it to work even with cut-n-pasted code and I'm wondering if I'm missing something trivially simple that my eyes are too bugged out to see. The full code is here:

<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function signup() {
    alert("Form is " + document.signup_form);
    document.signup_form.submit() ;
}
-->
</script>
</head>

<body>

  <?php
    echo("Submit is [" . $_POST['submit'] . "]");
  ?>

  <form method="post" name="signup_form" id="signup_form" action="" >
    <input type="text" name="from_email" placeholder="e-mail address"><br>
    <input type="submit" name="submit" value="Send Email"> 
    <a href="javascript:signup()">Sign Up!</a><br>
  </form>

</body>
</html>

The input submit element ("Send Email") works fine. The hyperlink ("Sign Up!") also works fine and calls the javascript function so that the alert() box in the function shows up.

So, it's just the submit() call that's not doing anything--I even printed out document.signup_form in an alert() box to confirm that it's defined (it is). So what am I missing here?

Thanks for any help!

  • 写回答

2条回答 默认 最新

  • doukuangxiu1621 2019-05-25 06:58
    关注

    There is a weird thing with how forms work with Javascript - each field is accessible by using formElement.fieldName. Unfortunately, that means that if you name a field input submit, all of a sudden the built-in formElement.submit() function is replaced by your input element. So in your code, document.signup_form.submit() is failing because it is calling the element, not the method, and you can't call an element as a function. See this SO QA for details.

    The fix is easy - change:

    <input type="submit" name="submit" value="Send Email"> 
    

    to:

    <input type="submit" name="submitBtn" value="Send Email">
    

    Also, as others have noted, you will want to give your form a valid action. Also, in general it might be preferred to access things by id (document.getElementById()) instead of by things like document.signup_form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?