jQuery events not firing - javascript

I have been trying to get this to work. Basically I have a search box that has a default string in it (i.e. Search) and it should go away when the user clicks on the input field.
Here is the code:
HTML:
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' value="Search <?php print $row[0]?> tweets!" autocomplete="off" />
</form>
Javascript/jQuery: (defaultString is a global variable that has the value of the textbox)
function clearDefault() {
var element = $('#searchBox');
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
element.css('color','black');
}
$('#searchBox').focus(function() {
clearDefault();
});

Problem is here:
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
Change it with:
if(element.val() == defaultString) {
element.val('value');
}
Update: Check it here:
http://jsfiddle.net/mr3T3/2/

The problem was that the event binding was not inside the $(document).ready() handler.
Fixed:
function clearDefault() {
var element = $('#searchBox');
if(element.val() == defaultString) {
element.val("");
}
element.css('color','black');
}
$(document).ready(function() {
$('#searchBox').focus(function() {
clearDefault();
});
});

It could be that event in fact is firing and your problem is in
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
is "defaultString" properly defined?
put a simple alert() inside clearDefaults() and see if the event works.

i don't think clearDefault is reusable function, so don't create unnecessary function for small block of code. See the following code sample, i added a small improvement in your functionality.
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' default="Search tweets!" value="Search tweets!" autocomplete="off" />
</form>
$(document).ready(function() {
$("#searchBox").focus(function(e){
var $this = $(this);
if($this.val() == $this.attr('default')) $this.val('');
else if($this.val().length == 0 ) $this.val($this.attr('default'));
});
$("#searchBox").blur(function(e){
var $this = $(this);
if($this.val().length == 0 ) $this.val($this.attr('default'));
});
});
I added a default attribute to store default value and used it later on blur event.
See the example in jsFiddler

Related

Reload the document to reset the game when it running [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Do a function if specific word is submitted in textbox

how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work
Heres the code
<form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)">
</form>
<div id="canvasDiv" width="500" height="10"></div>
<script type="text/javascript" src="robotti.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 500, 500);
document.getElementById("canvasDiv").onmousedown = function() {
jump(); }
//document.getElementById("canvasDiv").onkeypress = function() {
//move(); }
document.getElementById("canvasDiv").window.onkeypress = function(event) {
if (event.keyCode == 41) {
move();
}
}
</script>
This should work -:
var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
jump();
getElementById("canvasDiv").value = "";
}
Please use onkeyup instead of onkeydown
<!DOCTYPE html>
<html>
<body>
<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">
<script>
function keyCode(e) {
var text = (document.getElementById("canvasDiv").value).toLowerCase();
if(text == 'jump' || text == 'move'){
//call jump function here
alert("jump");
}
}
</script>
</body>
</html>
You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.
document.querySelector('input[type="text"]').addEventListener('keyup', function() {
switch (this.value) {
case 'move':
console.log('move!'); // Your actual function here
this.value = ''; // Reset value
break;
case 'jump':
console.log('jump!'); // Your actual function here
this.value = '' // Reset value
break;
}
});
Command the robot!: <input type="text" size="50">
Further reading:
Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector

Unable to get the value of the clicked button when two button elements shared the same name [duplicate]

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));

Javascript function gets called and then page resets back to initial state [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Prevent reload on form submit javascript [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Categories

Resources