jQuery .submit() with validation and without page refresh - javascript

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

Related

how to bind bootstrap loading button success / error on form submit

I'm trying to bind a bootstrap button with loading state to a form.
I would like the button to keep the data-loading state until the form is submitted. If the form errors out the data-loading should ideally stop or display a different message.
How can I achieve this?
My code for the button:
http://www.bootply.com/128762
what would be the best approach for a form that is not ajax?
Are You looking Something Like this Below
$('#loading-example-btn').click(function () {
if($("#txt").val().length > 0)
{
var btn = $(this)
$(this).attr('value','Loading');
}
else
{
$(this).attr('value','error On Submit');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="test" id="txt">
<input type="submit" id="loading-example-btn" value="Submit" data-loading-text="Loading...">
</form>

submit event not firing

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

javascript not working for URL re-direct

Can anyone help me with this script I'm trying to get working? I need a text box with a submit button, when a certain id is entered I need them to be re-directed to a certain site (below examples in the script are are yahoo, bing, etc).
This below is what I have so far, but the submit button doesn't show up and when the submit button is hit it doesn't seem to execute the script.
I just get a #? added to the url... I'm working in opencart so I think part of the problem might be with opencart.
<html>
<head>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap={
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
id=document.getElementById("siteid").value;
if (id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
event.preventDefault()
});
</Script>
</Head>
<Body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
</Body>
</Html>
Thanks for any help on this!
You should add your script at the end of the body.
You are calling document.getElementById("gobutton").addEventListener too early, at this point the button is not yet present in the page DOM, so no event is attached to it.
Working code :
<html>
<body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap = {
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
var id = document.getElementById("siteid").value;
if(id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
});
</script>
</body>
</html>
PS : try to indent your code prior to posting it !
I think if you remove that form tag ,it will solve all your problems.
I think there's no need for it be of submit type and have a form at all
Just remove those and the event.preventDefault()

Issues validating form on submit

I'm trying to validate email upon submit. Right now, I have it working so that it validates if I tab from the email to submit button, and also if I click the submit button directly. However, it doesn't validate if I press Enter from within the email field. Also, once it validates on clicking submit, I have to click the button again to actually submit.
The reason is because I start with type="button" rather than type="submit" on the submit input. This is because before when I started with type="submit" it would submit regardless of whether the email was valid or not.
So now, I start with type="button", validate the email, and then change it to type="submit" on valid emails. However, like I mentioned, it still isn't the most user-friendly (even though it does work as is). I'd like to add the user-friendly features described above. Here is the code I have (note: I'm using the Mailgun jQuery email validator for the validation part):
<form accept-charset="UTF-8" id="icpsignup" name="icpsignup" action="process.php" method="post">
<p>
<input type="text" onfocus="this.value=''" onblur="this.value=!this.value?'Enter name...':this.value;" class="txtbox_index" placeholder="Enter name..." value="Enter name..." name="fields_fname" id="fields_fname">
</p>
<p>
<input type="text" class="txtbox_index" onfocus="this.value=''" onblur="this.value=!this.value?'Enter email...':this.value;" name="fields_email" id="fields_email" Value="Enter email..." placeholder="Enter email...">
<input type="text" style="border: none;color: #fff;cursor: none; background-color:transparent; height:0px;" size="1" value="<?=$country_field;?>" name="fields_country" id="fields_country">
</p>
<div id="status"></div>
<p class="forfree">
<input type="button" value="Signup For Free!" id="validate_submit" class="signupbtn_new" name="submit">
</p>
<input type="hidden" value="<?php echo $paramstring ;?>" name="fields_trk">
</form>
<script src="js/vendor/jquery.js"></script>
<script src="js/mailgun_validator.js"></script>
<script>
// document ready
$(function() {
// capture all enter and do nothing
/* $('#fields_email').keypress(function(e) {
if(e.which == 13) {
$('#fields_email').trigger('focusout');
return false;
}
});
// capture clicks on validate and do nothing
/* $("#validate_submit").click(function() {
return false;
});*/
// attach jquery plugin to validate address
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
});
// while the lookup is performing
function validation_in_progress() {
$('#status').html("<img src='images/loading.gif' height='16'/>");
}
// if email successfull validated
function validation_success(data) {
$('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));
}
// if email is invalid
function validation_error(error_message) {
$('#status').html(error_message);
}
// suggest a valid email
submitHandler: function(form) {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
form.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
form.submit();
//return '<span class="success">Address is valid.</span>';
} else {
form.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}
}
// Another version of trying to using the Submithandler. I'm not sure if I'm supposed to use the validate or not.:
$(function() {
$("#icpsignup").validate({
submitHandler: function('icpsignup') {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
icpsignup.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
icpsignup.submit();
//return '<span class="success">Address is valid.</span>';
} else {
icpsignup.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}}
})
})
</script>
UPDATE: A MORE complete answer:
NOTE: this assumes you will be using jQuery 1.4.3 or higher
The SUBMIT event is sent to an element when the user is attempting to submit a FORM:
It can only be attached to <form> elements.
Forms can be submitted either by clicking an explicit:
<input type="submit">,
<input type="image">, or
<button type="submit">,
or
by pressing Enter when certain form elements have focus.
NOTE: *Depending on the browser, Enter may only cause a form submission if:
the form has exactly one text field, or
only when there is a submit button present.
Therefore, your code shouldn't rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key which is character code 13.
Here is information about how to use the .keypress() handler from jQuery.com
Here is a chart comparing all ASCII character/key codes, HTML escape codes, and they keys/character they represent.
You can get more detailed information at the jQuery.com site .submit() page HERE.
In your scenario (and most), I would use a <input type="submit"> button and capture the SUBMIT event.
In the submit handler callback function:
$( "form#icpsignup" ).submit(function( evt ){
//...
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
//...
}
You will need to validate your <form> (i.e. use whatever code, statement, etc. on one or more input fields). Then upon...
success - use a return true statement
failure - use an evt.preventDefault(); where evt is the argument passed to your submit handler.
.
Below is a detailed example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'correct' to validate.</p>
<form action="javascript:alert('success!');"
<div>
<input type="text">
<input type="submit">
</div>
</form>
<script>
// "function( evt )" is an anonymous function. It *is* your handler
$( "form" ).submit(function( evt ) { // evt is the *event* object.
// name it whatever you'd like.
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return true;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
evt.preventDefault();
});
</script>
</body>
</html>

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/

Categories