David Foie Gras
David Foie Gras

Reputation: 2070

<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;
    }
  }
});
<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>

This code is alerting when I click submit button.

I write onsubmit in the html form tag, but It seems not working.

How can I do this?

What I want to is that I can treat some stuff before form post. So I think I need those functions.

Upvotes: 3

Views: 7034

Answers (3)

Emad Morris Zedan
Emad Morris Zedan

Reputation: 301

for me, it was because I put the required attribute which prevents onsubmit=""

Upvotes: 1

Bhumi Shah
Bhumi Shah

Reputation: 9476

You can do it like this. Remove function from $(function() {

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

Upvotes: 3

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16801

The make_alert function is not "global" so it can't be found.

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>

Upvotes: 6

Related Questions