JavaScript: add latest form event - javascript

I'm writing a plugin and like to add a function to a submit/onsubmit event, that should only fire if all existing submit/onsubmit events return true.
It is ensured that my javascript-file will be loaded at last, but I have no idea if there is already a listener on the submit event (e.g.from another plugin).
Let's assume I have this form:
<form action="" method="POST" onsubmit="return validateForm()" id="dummyform">
Mandatory field:<br>
<input type="text" name="required" id="required" value="">
<br><br>
<input type="submit" value="Submit" class="placeOrder">
</form>
the on submit-Event validates the form and maybe there are some other events listening on the submit event. The validate form could look like this:
function validateForm() {
var x = document.getElementById('required').value;
if (x == "") {
alert("required fields must be filled out");
return false;
}
return true;
}
Is there a way to ensure all existing listeners are executed and only if all return true, execute my function?
I tried something like this:
var classname = document.getElementsByClassName("hook");
Array.from(classname).forEach(function(element) {
let form = findParentForm();
bindEvent(form, 'submit', function(e){
e.preventDefault();
if(form.onsubmit() === false)
return false;
modal.style.display = "block";
return false;
});
});
BindEvent is just a function to support IE8. It does a element.addEventListener(eventName, eventHandler, false); or element.attachEvent('on' + eventName, eventHandler);

Related

Submit form after unbinding

$("#qwerq").submit(function (e){
e.preventDefault();
var check=0;
if($("#firstName").val() == "") {
check=1;
}
if(check!=1){
$("#qwerq").unbind("submit") ;
$("#qwerq").submit();
//$("#qwerq").trigger('submit', [true]);
}
});
When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.
I have tried using .submit() and .trigger("submit"). I have to manually click on submit again.
What should I add so that I don't have to click again?
Instead of unbinding the events, why won't you just prevent submitting only on error?
if(check === 1) return false;
return false in jQuery's event handler means preventDefault and stopPropagation.
I think you were trying to submit a form on a button click.
Then you need to make some changes in your code:
Provide an id to your form and change button type="button" (instead of "submit"):
<form id="form_1" action="yourserverpagename.php" method="post">
<input id="firstName" type="text" value="" />
<input id="qwerq" type="button" value="Send" />
</form>
Now your script should like below:
<script>
$("#qwerq").click(function (e) {
e.preventDefault();
var check = 0;
if ($("#firstName").val() == "") {
check = 1;
}
if (check != 1) {
//-- here is the way to submit the form using form id --
$('#form_1').submit();
}
});
</script>

Why is my form submitting when I hit enter on a textbox?

HTML:
<form name="prints" method="post" action="">
<input type="text" name="quantity_914" id="quantity_914" value="1" style="width:20px;" onblur="prints_change_quantity(event, this);" onkeyup="return prints_change_quantity(event, this); return false;" />
</form>
Javascript:
function prints_change_quantity(e, element)
{
var pid = element.id.replace('quantity_');
var code = (e.keyCode ? e.keyCode : e.which);
if("blur" == e.type || ("keyup" == e.type && code == 13))
{
e.preventDefault();
console.log(element.value);
}
return false;
}
Cancelling a keydown event won't stop a form from being submitted. You'll need to use keypress or keyup instead.
use the key press event rather using keyup.
<form action="#">
<input type="text" name="txt" onkeypress="handle" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
alert("Enter was pressed was presses");
}
return false;
}
</script>
If you want to use your existing function and don't want your form to submit you can just use jquery and prevent the form from submitting with your existing function.
Example
$(document).ready(function(){
$("#prints").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
});
});
I added an id of prints to the form alternatively you could use a name selector or some other selector...
Alternatively if you want to be able to submit the form at some point you could just add a jquery handler for keypress on the form and if its the return key cancel it.
$('#prints').keypress(function(e){
if ( e.which == 13 ) e.preventDefault();
});
Example 2
By default keyDown event is triggered when you hit enter for a html form. Whenever you attach an event to onkeyUp attribute the form takes the enter key action and submits the form as it has no effect, however if you explicitly specify onkeyDown event then your return prints_change_quantity(event, this); gets called and hence the form won't get submitted . Change your html code to call the JavaScript function as shown below:
<form name="prints" method="post" action="">
<input type="text" name="quantity_914" id="quantity_914" value="1" style="width:20px;" onblur="prints_change_quantity(event, this);" onkeydown="return prints_change_quantity(event, this); return false;" />
</form>
Hope this helps.

Attempting to prevent submitting empty form

I have a form in my HTML document, and it only has a "text" input, and a submit button.
I also have JavaScript that checks if the field is empty and returns true or false.
JSFiddle: http://jsfiddle.net/HBZ7t/
HTML:
<form onsubmit="checkNull();" method="post">
<input type="text" id="field">
<input type="submit">
</form>
JavaScript
function checkNull() {
var field = document.getElementById("field");
if(field.value !== "") {
return true;
}
return false;
}
However, the form can be submitted even if the text field is empty... Any suggestions?
You are doing nearly everything right, you just need to return the value from the function to the handler:
<form onsubmit="return checkNull();" method="post">
// -------------^^^^^^
In JavaScript you can use double exclamation points to check for lots of non-valid settings:
function checkNull() {
var field = document.getElementById("field");
if(!!field.value) {
return true;
} else {
return false;
};
FIDDLE
JS
var form=document.getElementById("form");
form.onsubmit=function(){
var field = document.getElementById("field");
if (field.value !== "") {
return true;
}
return false;
};
HTML
<form id="form" method="post">
<input type="text" id="field">
<input type="submit">
</form>
you can use event.preventDefault() to cancel a event, see mozila doc here
Also, check the very nice jQuery submit function and samples here
Check this sample: http://jsfiddle.net/HBZ7t/5/
$( "#target" ).submit(function( event ) {
if($('#field').val()=='')
{
alert('cancel event');
event.preventDefault();
}
});

How do I disable form onsubmit if there is an error?

I have a form that collects user data and inserts into a database. Before submission, the data is validated and upon submission the window closes. I'm using try/catch for error handling so when there is an error I do not want the window to close.
This is what the form line looks like:
<form target="_self" method="post" id = "questionnaire" class="validate" onsubmit="submit();window.close()">
Essentially what I'm trying to do is if there is an error onsubmit=""
Thanks
You need to handle the submit event of your form, and cancel the submission.
Here's a DEMO
Unobtrustive Javascript without jQuery
//Get the form element.
var form = document.getElementById('questionnaire');
//Declare your event handler
var onMyFormSubmit = function (e) {
e = e || window.event; //Get the event if it's not passed in.
if (!valid) { //Do your validation here.
e.returnValue = false;
e.preventDefault();
return false;
}
};
//Attach an event handler to the submit event.
if (form.addEventListener) {
form.addEventListener('submit', onMyFormSubmit, false);
} else {
form.attachEvent('onsubmit', onMyFormSubmit);
}
Like this:
<script type="text/javascript">
function submit()
{
// do error checking
if ( /*passes*/ )
return true;
else
return false;
}
</script>
<form target="_self" method="post" id="questionnaire" class="validate" onsubmit="return submit();">

Javascript function fires twice on clicking 'Submit' button

I'm trying to insert records into DB using AJAX. I'm not sure why, but it seems the javascript function referenced in the onclick tag of the submit button gets fired twice, and hence I get two records in my DB per click.
Placing alerts in the JS, I have managed to figure out that the problem is in the JS function getting called twice, and not the PHP script making two inserts. So, I'm not posting the PHP script, unless asked.
Here's the HTML for the form:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}
You are calling processInfo twice once in submit handler and once in click handler. This might be the reason.
Here onclick="processInfo()" and inside
$("#notify").submit(function() {
processInfo();
return false;
});
processInfo() is called twice, both here, when the form submits:
$("#notify").submit(function() {
processInfo();
return false;
});
and here, when you click the submit button:
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
You should remove one of them.
You are calling the processInfo() function twice: once on the form submit event, and once on the onclick on the input.
You should only attach the processInfo() function on the submit event. Remove the onlick dom0 event handler (inline scripts are to be avoided).
Also, do not use return false; as it prevents event bubbling. Use ev.preventDefault() instead.
$("document").ready(function() {
$("#notify").submit(function(ev) {
ev.preventDefault();
processInfo();
});
});

Categories

Resources