简体   繁体   English

"<form onsubmit="function();">不管用"

[英]<form onsubmit="function();"> is not working

 $(function() { function make_alert() { var text = $('#text_').val(); \/\/let suppose it as true if (true) { alert("yes_text"); return false; } else { alert("no_text"); return false; } } });<\/code><\/pre>
 <script src="https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/3.3.1\/jquery.min.js"><\/script> <form method="post" action="#" onsubmit="return make_alert()"> <textarea id="text_"> <\/textarea> <button id="btn_submit" type="submit" name="type" value="create_first"> Submit <\/button> <\/form><\/code><\/pre>

This code is alerting when I click submit button.当我单击提交按钮时,此代码会发出警报。

I write onsubmit<\/code> in the html form<\/code> tag, but It seems not working.我在 html form<\/code>标签中写了onsubmit<\/code> ,但它似乎不起作用。

How can I do this?我怎样才能做到这一点?

What I want to is that I can treat some stuff before form post<\/code> .我想要的是我可以在form post<\/code>之前处理一些东西。 So I think I need those functions.所以我认为我需要这些功能。

"

The make_alert function is not "global" so it can't be found. make_alert函数不是“全局”的,因此无法找到它。

Here's one solution 这是一个解决方案

  var make_alert = (function() { var text = $('#text_').val(); //let suppose it as true if (true) { alert("yes_text"); return false; } else { alert("no_text"); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form method="post" action="#" onsubmit="return make_alert()"> <textarea id="text_"> </textarea> <button id="btn_submit" type="submit" name="type" value="create_first"> Submit </button> </form> 

You can do it like this. 你可以这样做。 Remove function from $(function() { 从$(function(){中删除函数

https://codepen.io/creativedev/pen/eKdrdK https://codepen.io/creativedev/pen/eKdrdK

function make_alert() {
    var text = $('#text_').val(); //let suppose it as true
    if (true) {
      alert("yes_text");
      return false;
    } else {
      alert("no_text");
      return false;
    }
  }

对我来说,这是因为我放置了阻止 onsubmit="" 的 required 属性

"

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

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