dyamically change onclick functionality for a href jquery - javascript

I have a javascript function (to Save the form values) already defined globally in a common js file and now I need to override that with some other functionality based on some condition. Is there any way I can attach a javascript function to the a href onclick dynamically? I tried this way but it is not working. Can anyone please help me?
Parent html:
<a href="#" onclick="Save();" id="SaveLink"/>
Common.js:
function Save()
{
//do something
}
My child html calls ValidateForm function (available in Common.js) to validate the form
and if it is not valid then stop calling the global Save() function.
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
$("#SaveLink").on("click", "Save();"); //call the global Save function
}
}
Updated Code:
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
//call the global Save function
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
Save();
e.preventDefault();
});
}
}

<a href="#" id="SaveLink" onclick="$.Save(this.id);"/>
JQuery Code:
$.Save=function(id)
{
//by using id you can apply your conditions
}

You need to remove onclick event
function ValidateForm() {
var responseValid = false; //false for now
if (!responseValid) {
//Remove onclick attribute
$("#SaveLink").removeAttr('onclick');
//OR
$("#SaveLink").prop("onclick", null);
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
} else {
//call the global Save function
$("#SaveLink").on('click', Save);
}
}

You should pass function handler, not String:
$("#SaveLink").on("click", Save);
EDIT:
To prevent onclick in page you should remove it on DOM ready event. For example:
$( function() {
$( '#SaveLink' )[ 0 ].onclick = null;
});

function ValidateForm()
{
var isSave= true;
//do your form validation
if(validation fail) //if validation fail set isSave is false
isSave=false;
return isSave;
}
function save()
{
if(ValidateForm()) //it will only execute validation is not fail
{
// do your code
}
}
OnClick just call save function only

Related

How to return a value from a jQuery event function to the parent function?

I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}

jQuery callback function pass event

I have a click event as follow which works fine:
$('#showmenu').off('click').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
show_menu();
return false;
});
where show_menu is:
function show_menu(e) {
if (!collapseForm.is(':visible')) {
collapseForm.show();
showMenu.removeClass(chevronDown).addClass(checvronUp);
searchAgain.hide();
} else {
collapseForm.hide();
showMenu.removeClass(checvronUp).addClass(checvronDown);
searchAgain.show();
}
}
I would like to be able to do something like that:
$('#showmenu').off('click').on('click', show_menu(e));
Is it possible to pass "e" to the callback function by doing the following?
function show_menu(e) {
e.preventDefault();
e.stopPropagation();
if (!collapseForm.is(':visible')) {
collapseForm.show();
showMenu.removeClass(chevronDown).addClass(checvronUp);
searchAgain.hide();
} else {
collapseForm.hide();
showMenu.removeClass(checvronUp).addClass(chevronDown);
searchAgain.show();
}
return false;
}
The event object is passed to the function when the function is called (by the event firing).
You have to pass the function to the on method.
$('#showmenu').off('click').on('click', show_menu);

Adding and removing events in javascript

I require to keep track on what events are on my dom elements and correspondingly add or remove event-listeners.
The way I keep track of the events right now is as follows ,
To add events :
function addListenerIfNone(addTo,eventType, func) {
if(addTo.id){
if (addedListeners[addTo.id+eventType]===eventType)
{
console.warn('event not added');
return;
}//event is alreaday present
addedListeners[addTo.id+eventType]= eventType;
addTo.addEventListener(eventType, func,true);
console.warn('event added');
}
else{
console.warn("Elements needs to have id attribute");
return false;
}
}
To remove added events:
function removeListenerIfPresent(addTo,eventType, func) {
if(addTo.id){
if (addedListeners[addTo.id+eventType]){ //event present
addedListeners[addTo.id+eventType]= null;
addTo.removeEventListener(eventType, func,true);
console.warn("event removed!");
}
else{
console.warn("event not removed!");
return false;
}
}
else{
console.warn("Elements needs to have id attribute");
return false;
}
}
I have a elements where I need to add click event dynamically as mousemoves overs it to different positions
My code(psuedo):
addListenerIfNone(ele,'mousemove',moveAttackFromHex);
var moveAttackFromHex=function(e){
if (e.pageY='someposition')
{
x='some value';
}
else
{
x='some other value';
}
function moveUnitHandler(){
unitObj.moveToAttackUnit(hexMeshObj.selectedUnit,x);
};
removeListenerIfPresent(ele,'click', moveUnitHandler); //this doesn't remove the event ,even tho it is present and I end up having lot of click events
addListenerIfNone(ele,'click', moveUnitHandler);//add new event listener once the previous is removed
}
I can't keep removeEvent after add event as I it would remove the event right away,
I don't want to use jquery as I have not used it for the entire project but as I last resort I may end up using it.
note: the dom element already has a click event referencing another function,if this makes a difference but I think not..
Thanks
Your code like it is would have problems with the javascript hoisting process. You also need to pass to the removeEventListener function the same callback you registered with the addEventListener function and that it doesn't seem to happen in your code since a new instance of an inner function is created every time in pure javascript.
addedListeners = {};
function addListenerIfNone(addTo, eventType, func) {
if(addTo.id) {
if (addedListeners[addTo.id+eventType] === eventType)
{
console.warn('event not added');
return;
}//event is alreaday present
addedListeners[addTo.id+eventType]= eventType;
addTo.addEventListener(eventType, func, true);
console.warn('event added');
}
else{
console.warn("Elements needs to have id attribute");
return false;
}
}
function removeListenerIfPresent(addTo, eventType, func) {
if(addTo.id){
if (addedListeners[addTo.id+eventType]){ //event present
addedListeners[addTo.id+eventType]= null;
addTo.removeEventListener(eventType, func, true);
console.warn("event removed!");
}
else{
console.warn("event not removed!");
return false;
}
}
else{
console.warn("Elements needs to have id attribute");
return false;
}
}
function moveUnitHandler() {
console.log("moveUnitHandler");
};
var moveAttackFromHex = function(e) {
console.log(addedListeners);
if (e.pageY = 'someposition') {
console.log("if");
}
else {
console.log("else");
}
removeListenerIfPresent(ele, 'click', moveUnitHandler);
addListenerIfNone(ele, 'click', moveUnitHandler);
}
var ele = document.getElementById("ele");
addListenerIfNone(ele, 'mousemove', moveAttackFromHex);
Obs: you probably also have a typo in the statement: if (e.pageY = 'someposition'), maybe it should be: if (e.pageY === 'someposition')

Jquery how to turn .off() to .on()

I have Jquery click event and i want to prevent multiple click before executing my function UpdateItemStatus(this.id);, so i have tried below code using on/off event,
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
$(this).off(e);
UpdateItemStatus(this.id);
$(this).on(e);
}
});
but how do i turn .on? as it's not working, not able to click again.
How about having a global variable which decides the button click action?
Something like this?
var clickevent = true;
$('#tableItems').on('click', 'tr', function (e) {
if(clickevent){
if ($(e.target).closest("td").hasClass("cssClick")) {
clickevent = false;
UpdateItemStatus(this.id);
clickevent = true;
}
}
});
if UpdateItemStatus function has ajax then i recommend you to put clickevent = true inside success of that ajax
You don't need to use off() for your code. Use return false:
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
return false;
} else{
//do stuff here
}
});
I would probably use something like this :
var inputstate = false;
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
if(!inputstate){
inputstate = true;
setTimeout((function(element){
return function(){
UpdateItemStatus(element);
inputstate = false;
};
})(this),50);
}
}
});
the setTimeout used to "defer the call" of your UpdateItemStatus function.
Because if this listener is fired, (an other listener cannot be fired at the same time) the value of the boolean will change to the end state before that the next click will be handled
Seems like your UpdateItemStatus() uses some asynchronous call (ajax?), so here's how i would do it:
$('#tableItems').on('click', 'tr', function (e) {
var $td = $(e.target).closest("td");
if ($td.hasClass("cssClick")) {
$td.toggleClass("cssClick");
UpdateItemStatus(this.id).done(function(){
$td.toggleClass("cssClick");
});
}
});
and in UpdateItemStatus:
function UpdateItemStatus(id){
//do stuff
return $.ajax(...);
}

Passing the result of click event to invoking function

Let's say I have a function that is creating a 'confirm or cancel' dialog dynamically and binding click events to the OK and Cancel links.
function confirmOrCancelDialog() {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
return true;
});
$dialog.find('a.cancel').click(function() {
//close dialog
return false;
});
}
Then, I am invoking the creation of this dialog from another function. I want to pass the result of the interaction to the invoking function.
function performAction() {
var clickResult = confirmOrCancelDialog();
if (clickResult === true) {
//do some stuff
}
}
Any guidance on how to do this would be appreciated. Thanks.
function confirmOrCancelDialog(someStuff) {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
someStuff(true);
return true;
});
$dialog.find('a.cancel').click(function() {
//close dialog
someStuff(false);
return false;
});
}
function performAction() {
confirmOrCancelDialog(function(clickResult){
if (clickResult === true) {
//do some stuff
}
});
}
You could just add an on click event to all anchors within the dialog object, and then check to see if the clicked anchor has the confirm class (or cancel, either one) and return accordingly:
$('.dialog a').on('click', function(event) {
if ($(this).hasClass('confirm')) { return true; }
return false;
});
Try this:
function confirmOrCancelDialog(callback) {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
callback(true);
});
$dialog.find('a.cancel').click(function() {
//close dialog
callback(false);
});
}
function performAction() {
confirmOrCancelDialog(function(clickResult){
if (clickResult === true) {
//do some stuff
}
});
}

Categories