Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.
Related
I'm new to javascript, but I've searched extensively about this and tried dozens of different alternatives. Most of them did nothing at all, others prevented the form from submitting!
I have the following form:
<form name="buy" action="process_order.php" method="post">
<input type="hidden" name="itemid" value="{$itemid}">
<button type="submit" id="submit" name="submit" class="btn btn-sm btn-success">Buy</button>
</form>
I want to prevent double submissions by either disabling the submit button after submit or just make it disappear, whichever works best.
I have tried multiple JS approaches and I dont even know which one is best, so I wont provide one here to avoid confusion.
I'd be thankful if you could provide me a full javascript <script> snippet and anything else I eventually need. I would prefer to not use Ajax here, but let me know if that would help.
Many thanks!
You can use jQuery for this.
$('form[name="buy"]').on('submit', function() {
$('#submit').prop('disabled', true);
});
That will disable the submit button as soon as the form is submitted.
As #rolodex has pointed out submitting the form will refresh the page, thus the disabled button becomes enabled again. This is what I would do if not using Ajax (as #rolodex's answer does):
<form name="buy" action="process_order.php" method="post">
<input type="hidden" name="itemid" value="{$itemid}">
<button type="submit" id="submit" name="submit" class="btn btn-sm btn-success"<?php if(isset($_POST['itemid'])) echo ' disabled'; ?>>Buy</button>
</form>
Thus once someone has submitted the form, the button becomes disabled. This doesn't stop someone refreshing the page again without form data though, but neither does using Ajax. The only way to get around that would be to use cookies.
In order to prevent second submission after the first, you have to use AJAX, as far as I am concerned, because every time the form is submitted, the page will refresh and there will not be any indication if the form is already submitted or not. My approach here will use jQuery and here's how you do it.
First, remove the attribute action and method from your <form> which we will replace with the AJAX call. Just as simple as this;
<form name="buy">...</form>
Secondly, include the necessary jQuery library;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Then the script;
<script>
$(function(){
$('form').on('submit', function(){
var data = $(this).serializeArray()
$.post('process_order.php', data, function(r,s){
console.log(r)
});
// Updated answer (change submit button's ID to class instead);
$(this).find('.submit').prop('disabled', true);
return false;
})
})
</script>
And that's all. It's identical to #Styphon's answer, but I believe that this is more complete and I hope this helps.
Cheers!
I use this (jQuery required):
<script>
var submiting = false;
$(function() {
$('form').submit(function() {
if (!submiting) {
submiting = true;
$('button[type=submit]').prop('disabled', true); //cosmetic
} else {
return false;
}
});
});
</script>
With this code, when the form is submitted, the boolean will prevent any further submission (ie. the user clicks really fast on the submit button) and will disable the button preventing further clicks.
But a much better aproach is described here:
Prevent double submission of forms in jQuery
Here is a neat solution
$('form').submit(function(){ //prevent multiple submit
$(':submit', this).click(function() {
console.log("submit prevented"); // Debug purpose.
return false;
});
});
If you submit form for instance 4 times, you will see the 3 "submit prevented" output.
$("#btn").trigger("click");
$("#btn").trigger("click");
$("#btn").trigger("click");
$("#btn").trigger("click");
I'm trying to submit a form using an anchor tag. However, the validation function doesn't seem to get triggered. I've since replaced the anchor with a submit button and it now works. Still, I'm curious why the previous anchor link didn't work.
The code is
function validate() {
/* validation code here */
return status;
}
<form id="myForm" action="/response_page.php" onsubmit="return validate();" method="POST">
<!-- form elements here -->
Submit
</form>
With this code, clicking the link goes straight to *response_page.php*. But when replaced with a submit button
<input type="submit" value="submit" />
WITHOUT changing the validate function and form tag, the validate function is called correctly. What's wrong with the anchor?
Thanks
This is expected behavior.
From the MDN on the submit function :
The form's onsubmit event handler (for example, onsubmit="return
false;") will not be triggered when invoking this method from
Gecko-based applications. In general, it is not guaranteed to be
invoked by HTML user agents.
If you want to validate your code in your link, just call the validate function explicitely :
<a id=subbut href="#" class="submit_button">Submit</a>
...
document.getElementById('subbut').addEventListener('click', function(){
if (validate()) document.getElementById('myForm').submit();
});
I want to prevent a form from being submitted using jQuery and instead run a function when the user wants to submit.
Here's my forms markup:
<form action="" method="post" id="msg-form">
<p><textarea name="msg"></textarea><input type="submit" value="Send"></p>
</form>
And my Javascript code:
$('#msg-form').submit(function() {
return false;
}
However, when I press the submit button, the form still gets sent and the page refreshes. How can I properly prevent the form from submitting?
It seems the event handler is not even executed, thus I assume the form could not have been found. Try enclosing your code within handler executed when the DOM is ready. In jQuery it can be simply done like that:
$(function(){
$('#msg-form').submit(function(event) {
event.preventDefault();
// code executed when user tries to submit the form
});
});
Also, as you can see above, you can prevent default behaviour of the form when it is being submitted.
The submit event is not actually being bound to the form element. You may have forgotten to bind it after the DOM was loaded!
Put the event binding inside of $(document).ready(function() { or load the script at the bottom of the page (after all of the elements have loaded).
$('#msg-form').submit(function(e){
e.preventDefault();
});
You could not give the users a real submit button and only submit the form using JS after validation:
HTML
<form action="" method="post" id="msg-form">
<p><textarea name="msg"></textarea><input id="submit" type="button" value="Send"></p>
</form>
JS
$('#submit').on('click', function() {
// validate
$('#msg-form')[0].submit();
});
Try:
$("#msg-form").submit(function (e) {
e.preventDefault();
});
This works
<form action='' onsubmit="return false;">
As does this
<form action='' onsubmit="doSomeWork();return false;">
I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven
You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.
You'd have a javascript function something like this:
function check_it_all() {
if (all_ok) {
return true;
} else {
return false;
}
}
And the form
<form action=..... onsubmit="return check_it_all();">
....
</form>
Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.
You should still use the submit button to submit the form, that is the correct behavior.
Input validation should be done using the <FORM>'s onSubmit event.
It should look something like this:
<script>
function validate() {
var isFormValid = whatever; // validate form
return isFormValid;
}
</script>
<form action="your.php" method="POST" onSubmit="return validate()">
<!---fields--->
</form>
The function validate() returns a bool.
This will stop the submission if validate() returns false.
<input type="submit" onclick="return validate()" value="click" />
I am an aspx.net developer so I am used to putting the validation call on the button.
If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.
Such as
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:
<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/>
<div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/>
<script type="text/javascript">
//<![CDATA[
var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {})
//]]>
</script>
You should add an event handler to the form itself which calls a function to decide what to do.
<form onsubmit="return someFunction();">
And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.
Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.
Trap the event and cancel it.
It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.
You could use a regular button that submits the form on click instead of your submit button.
If you want the enter key to work in other fields, just handle it there and submit the form.
in the input element for the button do:
<input type='submit' value='submit' onclick='submiFunction(); return false;'>
or on the form itself
<form blabla onsubmit='someAjaxCall(); return false;'>
Which should stop the form from submitting.
the return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)