jQuery - how to trigger a function whenever a element enabled? - javascript

I am looking to fix my function to work, whenever the element enabled. at present it's not working..
here is my try:
var x = function () {
input = $('#username');
if (input.prop('disabled')) {
console.log('i am enabled'); // how to trigger this?
}
}
x();
$('#enable').on('click', function(){
$('#username').removeAttr('disabled');
})
Live Demo
Note: my App always remove the attribute disabled

I have created a fiddle (modified your fiddle) Hope this is the solution you require
fiddle
Code Snippet:
if (typeof attr !== 'undefined' && attr !== false) {
console.log('i am disabled'); // how to trigger this?
}

Related

Why a missing function parameter has a value of "[object Object]"?

I have a signup modal window, that should appear under two circumstances:
a) a button is clicked on the webpage;
b) the webpage has "#modal" in the URL (e.g. mydomain/mypage.html#modal) - in this case the webpage should load with the modal window above it.
Scenario A works as follows:
Html
<a href='#' class='button signup' data-target='.signup-modal'>Find out more</a>
JS + JQuery
$(function() {
$('.signup').on('click', showModal);
});
Scenario B:
JS
$(document).ready(function(){
var hash = window.location.hash;
if(hash === '#modal'){
showModal('.signup-modal');
}
});
The showModal function works as follows:
function showModal(modalType) {
var getTarget = $(this).data('target');
if (!getTarget) {
var target = modalType;
} else {
var target = getTarget;
}
$(target).show();
return false;
}
This works.
However, my previous attempt to this function was slightly different:
function showModal(modalType) {
if (!modalType) {
var target = $(this).data('target');
} else {
var target = modalType;
}
$(target).show();
return false;
}
This didn't work with Scenario A.
I thought, that if the function has no parameter specified, it will get modalType = undefined, and then var target = $(this).data('target');. I added alert(target) and found out, that after clicking on the button, I was getting [object Object] as the value of target.
Can anyone please explain why?
First argument of an event handler callback is the event object. So if (!modalType) will never be true.
You could check if it is a string for the selector version. Something like:
if ( typeof modalType !== 'string' )
Here's a simplified example:
function doStuff(thing){
if(!thing){
// won't get called in the two scenarios used
console.log('no thing');
return
}
if(typeof thing === 'string'){
console.log('Argument is string:', thing)
}else{
// thing is event object
const event = thing;
console.log('Event type:', event.type);
console.log('Target:', event.target)
// also `this` will be the element instance event occurred on
console.log('Tagname:', this.tagName);
}
}
$('button').on('click', doStuff);
doStuff('SomeString')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>

delay() doesn't work second time jquery

I have a problem with the delay() of jquery. I'm using an if, else if condition with a variable:
var myvar = false;
function OpenAnimation(Clicked) {
if (myvar == true) {
$(Clicked).removeClass('open_peak');
myvar = false;
} else if (Clicked == 'an ID') {
$(Clicked).delay(500).queue(function () { $(this).addClass('open_peak') });
myvar = true;
}
The function is working fine with each ID passed in it. BUT the second time I run the function for an ID that already had and "lost" .open_peak (which is OnClick by the way), the class .open_peak does not apply to that element.
So when I open a window it goes:
} else if (Clicked == 'an ID') {
$(Clicked).delay(500).queue(function () { $(this).addClass('open_peak') });
myvar = true; //which tells me that a window(element) is indeed open
}
And when I close it:
if (myvar == true) {
$(Clicked).removeClass('open_peak');
myvar = false;//No window is opened
}
I have a lot more codes in there but it's .open_peak that isn't applying.
Here is a JSFiddle where you can see the issue: http://jsfiddle.net/at3eyLoL/
From the jQuery docs:
Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.
Add $( this ).dequeue(); in the function that is called after the delay.

JQuery trigger element itself in a bind

Can someone explain me why this snippet can't work ?
I can't use specific features like window.location, submit(), (instead of trigger()), because this function is bound to elements that are very differents.
$('a, button').bind('click', function(oEvent, oData) {
var oButton = $(this);
var bSkip = (oData && oData.skip);
if(true === bSkip) {
return true;
} else {
oEvent.preventDefault();
//oEvent.stopPropagation();
if(confirm('This is a confirm box')) {
$(oButton).trigger('click', { skip: true });
}
}
});
Thanks in advance ! ;)
In your case even though the click event gets fired the default behavior of the links may not be triggered because of the constraints imposed by the browser
If I understand what you are trying to do correctly(if the action s not confirmed then cancel the default behavior), then you can achieve it by the below... there is no need to fire the event again
$('a, button').bind('click', function (oEvent, oData) {
if (confirm('This is a confirm box')) {
return true;
} else {
oEvent.preventDefault();
}
});
Demo: Fiddle

Disable Select based on another element on the Same Row

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Preserving current click event jquery

I need to temporarily change the click event for an element as follows:
var originalEvent = '';
$("#helpMode").click(function (e) {
originalEvent = $("#element").getCurrentClickEventHandler();
$("#element").click(function (e) {
//Do something else
});
});
//Later in the code
$("#helpModeOff").click(function (e) {
$("#element").click(originalEvent);
});
How would I store the current function that is an event handler in a global variable for later reuse?
EDIT: Here's what im trying to do:
var evnt = '';
$("#helpTool").click(function (e) {
if(!this.isOn){
evnt = $("#Browse").data('events').click;
$("#ele").unbind('click');
$("#ele").click(function (e) {
alert('dd');
});
this.isOn=true;
}else{
this.isOn = false;
alert('off');
$("#ele").unblind('click');
$("#ele").click(evnt);
}
});
Here you go, figured it out:
Now with e.srcElement.id you can get either HelpMode or HelpModeOff and then can turn on/off your help stuff!
http://jsfiddle.net/zcDQ9/1/
var originalEvent = '';
$('#element').on('yourCustomEvent', function (e) {
// do stuff
alert(originalEvent);
$(this).toggleClass('toggleThing');
//test for helpMode or helpModeOff here now...
});
$("#helpMode").on('click', function (e) {
originalEvent = e.srcElement.id;
$("#element").trigger('yourCustomEvent');
});
//Later in the code
$("#helpModeOff").on('click', function (e) {
originalEvent = e.srcElement.id;
$("#element").trigger('yourCustomEvent');
});​
Okay. In jQuery 1.7 I guess it's a little different.
//get the handler from data('events')
$.each($("#element").data("events"), function(i, event) {
if (i === "click") {
$.each(event, function(j, h) {
alert(h.handler);
});
}
});
http://jsfiddle.net/yQwZU/
This is the reference.
Not sure if the following works with 1.7.
originalEvent = $('#element').data('events').click;
jQuery stored all the handlers in data. See here to learn more about data('events').
Personally, I think I would avoid manually binding and unbinding handlers.
Another way to approach this is to bind click events to classes, then all you need to do is add and remove classes from the appropriate elements when switching to/from help mode.
Here's a jsfiddle illustrating what I mean.
Switching to and from help mode then just involves adding removing classes:
$('#btnhelpmode').click(function(){
if(!helpMode){
helpMode = true;
$('.normalmode').addClass('helpmode').removeClass('normalmode');
$(this).val('Switch to normal mode...');
}else{
helpMode = false;
$('.helpmode').addClass('normalmode').removeClass('helpmode');
$(this).val('Switch to help mode...');
}
});
and you just create the handlers required, binding them to the appropriate classes:
$('#pagecontent').on('click', '#element1.normalmode', function(){
alert('element1 normal mode');
});
$('#pagecontent').on('click', '#element1.helpmode', function(){
alert('element1 help mode');
});
$('#pagecontent').on('click', '#element2.normalmode', function(){
alert('element2 normal mode');
});
$('#pagecontent').on('click', '#element2.helpmode', function(){
alert('element2 help mode');
});

Categories

Resources