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

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!

dsw8292301
dsw8292301 action属性缺少值
一年多之前 回复

2个回答

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.

dousong4777
dousong4777 谢谢! 重命名按钮就行了......我很高兴它比一些错字更微妙一点!
一年多之前 回复

Your <form> element is missing a value in it's action attribute. Quoting the specs:

You also have to specify the URL of the service that will handle the submitted data, using the action attribute

Link here

drtpbx3606
drtpbx3606 我实际上在action字段中有<?php echo $ _SERVER [“PHP_SELF”];?>,但在调试过程中将其取出。 你在技术上是正确的,但是,在旧学校的方式,它仍然有效,并且出于兼容性原因可能仍然存在:9。如果action是空字符串,请将action作为文档的地址。 注意:此步骤是故意违反RFC 3986,这需要在此处进行基本URL处理。 这种违规行为的动机是希望与传统内容兼容。 [RFC3986]
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐