Reputation: 2070
$(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
Reputation: 301
for me, it was because I put the required attribute which prevents onsubmit=""
Upvotes: 1
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
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