submit event not firing - javascript

I want to submit a form when changing a drop down menu and want to prevent the page from reloading.
<script src="jquery-1.9.1.min.js"></script>
$(document).ready( function(){
$('#adv_search').submit( function(e){
alert('form submitted');
e.preventDefault();
});
});
<form id="adv_search" name="adv_search" method="post">
<select name="state" id="state" onchange="document.adv_search.submit()">
------
</select>
</form>

The plain javascript's submit() will trigger the natural submit process of a form, you cannot bypass it with a jquery's submit. So it is better to use jQuery alone for doing this,
$(document).ready(function() {
$("#state").change(function() {
$('#adv_search').submit();
});
$('#adv_search').submit(function(e) {
alert('form submitted');
e.preventDefault();
});
});
DEMO

Related

Form preventDefault not working

I have a button that submits a hidden form:
<a href = "javascript:;" onclick = "document.getElementById('work-for-form').submit();">
Form:
<form id="work-for-form" action="localhost/update" method="PUT" style="display: none;">
{{ csrf_field() }}
</form>
And my js:
$("#work-for-form").submit(function(event){
event.preventDefault();
console.log(event);
});
But the form still loads a new page.
What am i doing wrong?
Thanks
The onclick event on your a is too strong to prevent the submission of the form. I would suggest the following to fix this:
<a href="javascript:;" >form submit</a>
<form id="work-for-form" action="/update" method="PUT" style="display: none;">{{ csrf_field() }}</form>
<script>
$("a").on("click",function(){
$("#work-for-form").submit();
})
$("#work-for-form").submit(function(event){
alert('intercept');
event.preventDefault();
console.log(event);
});
</script>
see also https://jsfiddle.net/9hta6f48/
You can use return false or you can use eventListeners
<form onsubmit="alert('stop submit'); return false;" >
Or
function mySubmit(){
alert('Will not submit');
return false;
}
</script>
<form onsubmit="return mySubmit();" >
Or event listeners
var myFuncRef = function(event) { event.preventDefault() }
element.attachEvent('onclick', myFuncRef);
Your code must be inside $(document).ready or must be after the form is rendered,
$(document).ready(function(){
$("#work-for-form").submit(function(event){
event.preventDefault();
console.log(event);
});
});

jQuery .submit() with validation and without page refresh

I have a problem that others seem to have, but I cannot get the recommended solution (i.e., "return false;") to work. Any help would be great!
Description:
When the form is submitted, I want to validate the input is in the correct format (i.e., type="email") and launch an alert (i.e., "Form submitted.") without the page refreshing. Currently, the alert does not appear and the page refreshes.
Test Code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- JavaScript -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<!-- Form -->
<form>
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<!-- Alert on Submission -->
<script>
console.log("Ready to Go!");
$('#submit').submit(function () {
alert("Form submitted.");
return false;
});
</script>
</body>
</html>
You will want to catch the submit event of the form. There is no submit event on a button.
$('form').submit(function () {
if (*everything ok*) {
alert("Form submitted.");
} else {
return false;
}
});
Ideally you would help identify your <form>, either with an ID or a class, i.e.:
<form id="xyz-form">
And then change your selector to:
$('#xyz-form').submit(...);
Now this is only to stop the form from submitting when there are errors. When return false; isn't the path the submit callback takes, your page is going to refresh. If you want to submit the data to the server without a refresh, you will need to approach this differently.
Give your form an ID, and change your jquery to use #formid instead.
For example :
<form id="form">
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<script type="text/javascript">
$('#form').submit(function () {
alert("Form submitted.");
return false;
});
</script>
The event handler attached to the submit function in jQuery can be the form element or a div element. Read more on jQuery API
You can implement a click event when the user clicks on the submit button without its default submitting behavior with jQuery's preventDefault function
console.log("Ready to Go!");
$('form').submit(function () {
alert("Form submitted.");
return false;
});
$("#submit").click(function(e){
if (hasError){
e.preventDefault();
}
else{
alert("success");
}
})
The if and else statements are created for simple validation. For the scope of your question, I leave most of the coding for your creativity. But you can basically create a simple function to check for errors with the user inputs, if there are errors,prevent the submit button's default submission behavior. If the inputs are not empty and if inputs are free of errors, alert the user that the form has been submitted.
try this instead
$('#submit').click(function () {
alert("Form submitted.");
return false;
});
it'll accomplish what you want.
basically the click fires before the submit
try this snippet to clear things up
console.log("Ready to Go!");
$('#submit').click(function () {
alert("Form submitted.");
//return false;
return true;
});
$("form").submit(function( event ) {
alert("woot woot");
});

Can't use JQuery form validation with two buttons html form

HTML:
<form id="myForm">
<fieldset>
<ol>
<li>
<label for="data">Data</label>
<input id="data" name="data" type="text" placeholder="Ex.º: 14-02-2014" required>
</li>
<li>
<label for="conta">Conta</label>
<input id="conta" type="text" name="conta" placeholder="Ex.º: " required>
</li>
</ol>
<input id="oknovo" type="submit" value="OK & Novo" />
<input id="okfechar" type="submit" value="OK & Fechar" />
</fieldset>
</form>
JS:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
if (form.valid()) {
$("#myForm input[type=submit]").click(function (event) {
botao = $(this).attr('id');
alert("clique " + botao);
});
};
});
I want to validate the form using JQuery validation plugin.
If it is valid according to the rules specified in the HTML form, then identify which of the buttons was clicked. The validation plugin is working but the form is never valid, therefore the function is never called to alert the id of the button.
You may see a live JSFiddle here.
If the form isn't valid at DOM ready (which it will never be), then your code to add the event handler to the button won't run. You should consider running your validation on a different event, say when the text in the textbox changes.
Example:
$('input[type=textbox]').change(function() {
// put your validation code here.
});
Put your validation inside the click event, and it starts working:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
$("#myForm input[type=submit]").click(function (event) {
if (form.valid()) {
botao = $(this).attr('id');
alert("clique " + botao);
}
event.preventDefault();
});
});
Working fiddle
Try adding event.preventDefault();
$("#myForm input[type=submit]").click(function (event) {
event.preventDefault();
botao = $(this).attr('id');
alert("clique " + botao);
});

jQuery Validate doesn't remove error if value is auto-inputted via JavaScript

My HTML looks like this:
<form id="mainform" method="post">
<input type="text" class="required" name="receiver" />
<span id="clickMe">Click me</span>
<input type="submit">
</form>
And my JavaScript is as follows:
$(document).ready(function () {
$("#clickMe").click(function() {
$("input[name=receiver]").val("Clicked");
});
$("#mainform").validate({
submitHandler: function (form) {
alert("Success!");
return false;
}
});
});
Fiddle: http://jsfiddle.net/Y9RFt/2/
If you submit leaving the input empty, an error appears.
If you click the 'Click Me' span, the input is auto-filled, but the error remains until you submit the form. If you type something instead, the error disappears instantly.
Is there a way to emulate user input so that the error disappears on click?
Simply use the built-in .valid() method to force an immediate validation test of the form.
$("#clickMe").click(function () {
$("input[name=receiver]").val("Clicked");
$("#mainform").valid(); // <<-- Add this line to force a test
});
DEMO: http://jsfiddle.net/Y9RFt/8/
Got it. The solution is to simply blur the input:
$("input[name=receiver]").val("Clicked").blur();
Fiddle: http://jsfiddle.net/Y9RFt/7/

Form submit through AJAX not working

My form will not submit through AJAX to show the return of the PHP page, 'myscript.php'.
This is the HTML I'm using:
<form name="myform" id="myform" method="post" action="#" enctype="multipart/form-data" accept-charset="utf-8" class="taxonomy-drilldown-dropdowns">
<ul>
<li>
<label>Destination:</label>
<select name="city" id="city">
<option class="level-0" value="atlanta">Atlanta</option>
<option class="level-0" value="miami">Miami</option>
</select>
</li>
</ul>
<input class="srch_btn" type="button" value="{{submit-text}}" />
</form>
Here is the javascript earlier in the page:
jQuery(document).ready(function($) {
$('#city').change(function() {
$(this).parents("form").submit();
});
$('#myform').submit(function() {
$.post(
'myscript.php',
$(this).serialize(),
function(data){
$("#mydiv").html(data)
}
);
return false;
});
});
Here is the myscript.php:
<?php
if ($_POST['city'] == "atlanta") {
echo "Div contents 1";
}
if ($_POST['city'] == "miami") {
echo "Div contents 2";
}
?>
The submit button won't respond at this point or make an attempt to access the 'myscript.php' file. Help is appreciated. Thanks in advance!
It is better to use .closest() rather than .parents() in this case.. As parents selector gets all the ancestors that match the selector.
$('#city').change(function() {
$(this).closest("form").submit();
});
And to stop the Default action use e.preventDefault instead of return false
$('#myform').submit(function(e) {
e.preventDefault();
// Your code here
});
In you HTML code, I think you should change input type=button to input type=submit
<input class="srch_btn" type="submit" value="{{submit-text}}" />
Then when you click that button, the form will be submitted to your php page.
Also, about select change event in your jQuery code, I think you can just try following selector, as you have the name/id attribute available in your HTML.
$('#city').change(function() {
$('#myform').submit();
});
One issue with your code is that it does not actually stop the form from being submitted. return false; does not exactly work in jQuery in the way that you think it does. Instead, to stop the default action, you would have to do something like this.
$('#myform').submit(function(event) {
event.preventDefault();
http://api.jquery.com/event.preventDefault/
On top of that, if you don't want the form submit to take place, and you want to replace it with your own AJAX submition, why are you calling form submit at all in this code? Why not just put the AJAX directly into your change code?
dqhendricks was right - why use form submit when you can just access ajax directly? In the below example, I added a div (#responder) below the form to show the output. Try it -- you'll see that it works perfectly.
You really don't need the button, although I left it there, because the data is sent/received the moment the drop-down is changed. You will see your messages appear in the div I included below the form.
REVISED HTML:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="myform" id="myform" method="post" action="#" enctype="multipart/form-data" accept-charset="utf-8" class="taxonomy-drilldown-dropdowns">
<ul>
<li>
<label>Destination:</label>
<select name="city" id="city">
<option class="level-0" value="atlanta">Atlanta</option>
<option class="level-0" value="miami">Miami</option>
</select>
</li>
</ul>
<input class="srch_btn" type="button" value="Go" />
</form>
<div id="responder"></div>
REVISED JAVASCRIPT/JQUERY:
$(document).ready(function() {
$('#city').change(function() {
//var cty = $('#city').val();
$.ajax({
type: "POST",
url: "myscript.php",
data: "city=" + $(this).val(),
success:function(data){
$('#responder').html(data);
}
});
});
});

Categories