Is there any way to do the following:
validateLogin();
return false;
But actually like this..
validateLogin();
And here is the function:
function validateLogin(){
if(hi=true){
return true;
}
else{
return false
}
I want to attach this function for the event of a form being submitted, so if HI is false - i want to return false; meaning it will stop for form from submitting.. i know return false; will do so i just need to know how i can get this return back to the parent function?
Thanks in advance!
You can use it as follow:
return validateLogin();
however, as mmayo pointed out, don't forget about the return value:
event.returnValue = false;
You can eventually do that:
return validateLogin();
Note that your function code has some errors (maybe due to the simplification of the code you made to post this question?). You'd better write this method like that:
function validateLogin(){
...
return hi;
}
Note also that insted of having if (hi=true) {, you must write if (hi == true) {, or better if (hi) {...
I use the following to stop events...
event.returnValue = false;
cresentfresh inspired me to do some research... here is an article with a compatibility matrix.
There are also related threads on SO.
return validateLogin();
This should do what you want.
The standard way of stoping the default action of an event is:
event. preventDefault();
You may also want to prevent event propagation with event.stopPropgation(); to stop further event listeners from executing.
http://www.w3.org/TR/2001/WD-DOM-Level-3-Events-20010823/events.html#Events-Event
However, IE will not recognize this which is why you can set event.returnValue to false for IE.
eg:
if (event && event.preventDefault) event.preventDefault();
event.returnValue = false;
You can also return false from the event handler for events inlined in HTML.
<form onsubmit="return validateLogin()">
This is not considered best practice however.
Note: the event object is passed in as the first argument in your event listener.
eg:
function validateLogin(e) {
e; // is the event object
}
For IE you may need window.event.
function validateLogin(e) {
e = e || window.event; // is the event object
}
Try double == (IF I==5)
validateLogin() Function
function validateLogin() {
return hi;
}
HTML block
<form onsubmit="return validateLogin()">
...
</form>
Related
I have a handler attached to an event and I would like it to execute only if it is triggered by a human, and not by a trigger() method. How do I tell the difference?
For example,
$('.checkbox').change(function(e){
if (e.isHuman())
{
alert ('human');
}
});
$('.checkbox').trigger('change'); //doesn't alert
You can check e.originalEvent: if it's defined the click is human:
Look at the fiddle http://jsfiddle.net/Uf8Wv/
$('.checkbox').change(function(e){
if (e.originalEvent !== undefined)
{
alert ('human');
}
});
my example in the fiddle:
<input type='checkbox' id='try' >try
<button id='click'>Click</button>
$("#try").click(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
$('#click').click(function(event) {
$("#try").click();
});
More straight forward than above would be:
$('.checkbox').change(function(e){
if (e.isTrigger)
{
alert ('not a human');
}
});
$('.checkbox').trigger('change'); //doesn't alert
Currently most of browsers support event.isTrusted:
if (e.isTrusted) {
/* The event is trusted: event was generated by a user action */
} else {
/* The event is not trusted */
}
From docs:
The isTrusted read-only property of the Event interface is a Boolean
that is true when the event was generated by a user action, and false
when the event was created or modified by a script or dispatched via
EventTarget.dispatchEvent().
I think that the only way to do this would be to pass in an additional parameter on the trigger call as per the documentation.
$('.checkbox').change(function(e, isTriggered){
if (!isTriggered)
{
alert ('human');
}
});
$('.checkbox').trigger('change', [true]); //doesn't alert
Example: http://jsfiddle.net/wG2KY/
Accepted answer didn't work for me. It's been 6 years and jQuery has changed a lot since then.
For example event.originalEvent returns always true with jQuery 1.9.x. I mean object always exists but content is different.
Those who use newer versions of jQuery can try this one. Works on Chrome, Edge, IE, Opera, FF
if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
//Hey hooman it is you
}
Incase you have control of all your code, no alien calls $(input).focus() than setFocus().
Use a global variable is a correct way for me.
var globalIsHuman = true;
$('input').on('focus', function (){
if(globalIsHuman){
console.log('hello human, come and give me a hug');
}else{
console.log('alien, get away, i hate you..');
}
globalIsHuman = true;
});
// alien set focus
function setFocus(){
globalIsHuman = false;
$('input').focus();
}
// human use mouse, finger, foot... whatever to touch the input
If some alien still want to call $(input).focus() from another planet.
Good luck or check other answers
I needed to know if calls to the oninput handler came from the user or from undo/redo since undo/redo leads to input events when the input's value is restored.
valueInput.oninput = (e) => {
const value = +valueInput.value
update(value)
if (!e.inputType.startsWith("history")) {
console.log('came from human')
save(value)
}
else {
console.log('came from history stacks')
}
}
It turns out that e.inputType is "historyUndo" on undo and "historyRedo" on redo (see list of possible inputTypes).
You can use onmousedown to detect mouse click vs trigger() call.
I would think about a possibility where you check the mouse position, like:
Click
Get mouse position
Overlaps the coords of the button
...
Trying to cancel the sending of an empty form. Confused as there seems to be no reason why this doesnt work. Using firefox as my browser.
Could anybody explain why this code does not cancel the form being sent yet it fires the alert dialog.
addEvent(searchForm, "onsubmit", function(){
if(inputBox.value.trim() === ""){
alert("empty"); //this line gets called
return false; //this doesn't
}
});
Many Thanks
this is the addEvent function
function addEvent(element, listener, func){
if(element.addEventListener){
listener = listener.substr(2, listener.length);
element.addEventListener(listener, func);
} else {
element.attachListener(listener, func);
}
}
your handler should be
function(e){
if(inputBox.value.trim() == ""){
alert('empty');
e.preventDefault();
}
}
Normally regardless of the framework used handlers support passing the event itself as an argument.
addEvent is not a native javascript function.
use this instead..
searchForm.onsubmit = function(e){
if(inputBox.value.trim() === ""){
alert("empty");
e.preventDefault();
return false;
}
}
I try to prevent a form submitting, with the following script, but it always does. I have even tried preventDefault() on document load, but it does not work.
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
$("form").submit(function(e) {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
}
else{
$("span").text("Passwords do not match!").show().fadeOut(1000);
e.preventDefault();
}
});
You need to use preventDefault() to cancel the action. Note the parameter e that I added to the anonymous function call.
My suggestion, or the way I normally go about this is like this:
$("form").submit(function(e) {
e.preventDefault(); // form never fires unless I want it to
if( condition == true ) {
$(this).submit();
} else {
//Don't submit
}
}
Here is a great explanation of why preventDefault() > return false
In order for this to close I think I have found something, but it's absurd at best. My functions work when they are in a $(document).ready. Why? I would be glad to listen to your advice.
$(document).ready(function(){
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
});
I have a form, and when I submit him I execute multiple script. Here is my code:
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
//How to continue submitting?
}
Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?
Thank you
When you call $("#RequestCreateForm").submit(), the script will just run through the event handler again, and cause an infinite loop (as Koen pointed out in a comment on the accepted answer). So, you need to remove the event handler before submitting:
$("#RequestCreateForm").on('submit', function (e) {
e.preventDefault();
// do some stuff, and if it's okay:
$(this).off('submit').submit();
});
The last line needs to be in a conditional statement, otherwise it'll just always happen, and negate your e.preventDefault(); at the top.
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() === false) {
e.preventDefault();
//form was NOT ok - optionally add some error script in here
return false; //for old browsers
} else{
//form was OK - you can add some pre-send script in here
}
//$(this).submit();
//you don't have to submit manually if you didn't prevent the default event before
}
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false)
{
e.preventDefault();
return false;
}
//other scripts
}
All solutions here are too complicated or lead to javascript error, simpliest and clearest solution I guess:
jQuery("#formid").submit(function(e) {
if( ! (/*check form*/) ){ //notice the "!"
e.preventDefault();
//a bit of your code
} //else do nothing, form will submit
});
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
// Bypass the jquery form object submit and use the more basic vanilla
// javascript form object submit
$("#RequestCreateForm")[0].submit();
}
To avoid submit loops, an additional variable should be used.
var codeExecuted = false;
$('#RequestCreateForm').submit(function(e) {
...
if(!codeExecuted){
e.preventDefault();
...
functionExecuted = true;
$(this).trigger('submit');
}
});
Here is my approach to avoid the infinite loop.
In the form, I use a "button" with an id (e.g. <input type="button" id="submit" value="submit"/>) to mimic the submit button;
In the script I have something like this:
$('#submit').click(function() {
if(//validation rules is ok)
{
$("#RequestCreateForm").submit(); //assuming the form id is #RequestCreateForm
}
else
{
return false;
}
});
return; is the same thing as e.preventDefault();
try
$("#RequestCreateForm").trigger('submit');
How to remove and event listener with an Anonym function , with removeEventListener();
document.getElementById("object").onclick = function(e){
if(e && e.stopPropagation) {
e.stopPropagation();
} else {
e = window.event;
e.cancelBubble = true;
}
}
So I have this piece of code and the function what's called must be anonym I'dont know why but If it's not then doesn't works correctly, maybe beacuse of the event :|
But If it's anonym how can I remove it?
Well you havent added an actual event listener, you have just populated the onclick variable with a function to be run. So you should be able to just use something like this:
document.getElementById("object").onclick = false;
EDIT
Just tried it in jsFiddle and what I suggested works.
Just give it a null value, which is the starting value when onclick is not initialized:
document.getElementById("object").onclick = null