Jquery.Change not working - javascript

I am having some trouble with $.change in jQuery.
HTML
<button class="btn">Reset</button>
<p id="chg" class="change">Click Me</p>
<div class="onchange"></div>
JS
$('.btn').on('click', function() {
$('.change').text('Click Me');
$('.onchange').text('');
});
$('.change').on('click', function() {
$('.change').text('Nearly There');
});
$('.change').on('change', function() {
$('.onchange').text("Nice One");
});
Here is the link to Codepen
Basically what should happen is when "Click Me" is clicked the text will change to "Nearly There" then straight after "Nice One" should appear below.
However this isn't happening, I've tried both
$('.change').on('change', function() {});
$('.change').change(function() {});
And neither work.
Note
The code I have supplied is my test code, and is all relevant to what I'm trying to achieve.
Update
I wasn't aware the .change only worked for form controls, which would explain why it wasn't working.
Solution
CreMedian - Suggested the solution that I was looking for.
$('.change').on('DOMSubtreeModified', function() { });
I have updated the CodePen for future reference.

As indicated in the comments, the .change() event does not work with div elements.
One way you could get the same effect is with the following code:
$('.change').bind("DOMSubtreeModified",function(){
//action you want when the '.change' object changes
});
Javascript MutationEvent is not widely supported, so be careful if implementing this in production code.
Reference Link: http://help.dottoro.com/ljrmcldi.php

$('.change').on('change', function() {
in your example, .change is a div, and divs dont raise change events when clicked.
You probably wanted to just update both elements from the click event
$('.btn').on('click', function() {
$('.change').text('Click Me');
$('.onchange').text('');
});
$('.change').on('click', function() {
$('.change').text('Nearly There');
$('.onchange').text("Nice One");
});

Try with DOMSubtreeModified event.
$('.btn').on('click', function() {
$('.change').text('Click Me');
$('.onchange').text('');
});
$('.change').on('click', function() {
$('.change').text('Nearly There');
});
$('.change').on('DOMSubtreeModified', function() {
$('.onchange').text("Nice One");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button class="btn">Reset</button>
<p id="chg" class="change">Click Me</p>
<div class="onchange"></div>
Note: It will not supported by IE8 and older.
Demo in CodePen

The browser only fires change events for textbox, check/radio box and select list - all form elements. When something changes within your <div> or <p>, the browser does nothing to notify your javascript. Therefore, the listener .on('change' is not going to ever fire.
Here is a short lists of for elements that raise the event:
TextBox When Enter key is pressed
Radio/Check Box When the state is changed
Select List When the selected item is changed
Here is more on the event: Mozilla MDN onchange

do it like this
$('.change').text('Nearly There').trigger('change');
example
$('.btn').on('click', function() {
$('.change').text('Click Me');
$('.onchange').text('');
});
$('.change').on('click', function() {
$('.change').text('Nearly There').trigger('change');
});
$('.change').on('change', function() {
$('.onchange').text("Nice One");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<button class="btn">Reset</button>
<p id="chg" class="change">Click Me</p>
<div class="onchange"></div>

Related

jQuery off() not removing click handler

I have the following code:
$(document).ready(function () {
EnableModal();
});
function EnableModal() {
if (isModalEnabled) { return; }
// Initialize modal dialog
// attach modal-container bootstrap attributes to links with .modal-link class.
// when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
}
function DisableModal() {
$('body').off('click', '.modal-link');
}
I am attempting to turn this off under certain circumstances, so I am calling:
$('body').off('click', '.modal-link');
However, the button with the modal-link class is still allowing click events through. I see no errors in the developers console.
I have verified it is calling these correctly and that each is only being called once in my test case.
What am I doing wrong here?
I met this issue before. I wasn't sure what happened at the very beginning and wonder if it was because the selectors weren't actually the same. I checked them and found out they were the same but still couldn't remove the event handler.
I finally fixed this by giving a dummy function as event handler after I removed the original one.
function DisableModal() {
$('body').off('click', '.modal-link');
$('body').on('click', '.modal-link', () => {});
}
Feel free to use ES5 version if you don't like the lambda expression. as
$('body').on('click', '.modal-link', function(){});
Works fine here:
var isModalEnabled;
$(document).ready(function () {
EnableModal();
$(".disableModal").click(DisableModal);
});
function EnableModal() {
if (isModalEnabled) { return; }
// Initialize modal dialog
// attach modal-container bootstrap attributes to links with .modal-link class.
// when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
}
function DisableModal() {
$('body').off('click', '.modal-link');
}
body { font-family: sans-serif; }
[data-target='#modal-container'] {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click a few "Modal Link" buttons, and watch the button text turn bold. Then click the "Disable Modal" button, and click the remaining "Modal Link" buttons. The button text does <em>not</em> turn bold.</p>
<button class="modal-link">Modal Link</button>
<button class="modal-link">Modal Link</button>
<button class="modal-link">Modal Link</button>
<p><button class="disableModal">Disable Modal</button></p>
<button class="modal-link">Modal Link</button>
<button class="modal-link">Modal Link</button>
<button class="modal-link">Modal Link</button>
<p>To reset, click the "Run code snippet" button above.</p>
Without knowing the real cause of this, maybe the solution is to use namespaced events.
$('body').on('click.modal', '.modal-link', function (e) { });
and to remove it
$('body').off('.modal');
But I have a feeling it has nothing to do with this, but with the real issue is with the bootstrap modal. Maybe you need to clean up those attributes.
$('[data-toggle="modal"]').removeAttr("data-target data-toggle");

I'm trying to attach events using on() based on changing selectors

I have a button that can be in 2 different states (lets say Lock and Unlock). When I click on the button, I update the class on the button to reflect the binary opposite state. Each class has a different event attachment function using on(string, callback). For some reason the event being triggered remains the first callback assigned based on the original class.
HTML:
<button class="lock">Lock</button>
<button class="unlock">Unlock</button>
JavaScript:
$(document).ready(function() {
$('.lock').on('click', function() {
// Perform some magic here
console.log('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$('.unlock').on('click', function() {
// Perform some magic here
console.log('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
https://jsfiddle.net/c283uaog/ for testing.
Expected console output when clicking on the same button repeatedly:
Lock!
Unlock!
Lock!
Actual console output:
Lock!
Lock!
Lock!
Any assistance would be greatly desired
use event Delegation
$(document).on('click','.lock', function() {
$(document).on('click','.unlock', function() {
updated Demo
Or use in single function with toggleClass
$(document).on('click', '.lock,.unlock', function () {
$('#output').html($(this).attr('class'));
$(this).toggleClass('lock unlock').text($(this).attr('class'));
});
ToggleClass demo
I'd do it this way, attaching only one event: http://jsfiddle.net/jozu47tv/
$(".lock").on('click', function(e) {
e.preventDefault();
if($(this).hasClass("lock")) {
$(this).removeClass("lock").addClass("unlock");
console.log("lock -> unlock");
} else {
$(this).removeClass("unlock").addClass("lock");
console.log("unlock -> lock");
}
})
Use Event Delegation method, Try this updated fiddle,
$(document).ready(function() {
$(document).on('click', '.lock', function() {
$('#output').html('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$(document).on('click', '.unlock', function() {
$('#output').html('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
Probably, this question could answer you in a better way:
jQuery .on function for future elements, as .live is deprecated
$(document).on(event, selector, handler)
Change your html to this:
<button class="locker lock" >Lock</button>
<button class="locker unlock"">Unlock</button>
<div id="output">Output</div>
and your Js to this:
$(document).ready(function() {
$('.locker').on('click', function() {
if($(this).hasClass("lock")){
$(this).removeClass("lock");
$(this).addClass("unlock");
$(this).html("unlock");
}
else if($(this).hasClass("unlock")){
$(this).removeClass("unlock");
$(this).addClass("lock");
$(this).html("lock");
}
});
});

Attach one time event to dynamically added elements

I have a web page where there is a button, when the button is clicked a Textbox is added to a DIV. Here is a similar code that I'm working with:
HTML
<button class="addText">Add Textbox</button>
<div class="textCont">
</div>
JavaScript
$(document).on("click", ".addText", function() {
var textarea = $("<textarea/>", {class: "newText"});
$(".textCont").append(textarea);
});
$(document).one("focus", ".newText", function() {
alert("Great");
});
Fiddle: http://jsfiddle.net/ErRohitAgg/g3A7T/
What I'm trying to do is to show an alert for first focus of every textbox that is added. But, instead the focus event is executing only once, and not once for each Textbox.
Is there any way the event behaves according to the functionality I need??
Add the event handler to each textarea instead
$(document).on("click", ".addText", function() {
$("<textarea/>", {
'class': 'newText',
one : {
focus: function() {
alert("Great");
}
}
}).appendTo(".textCont");
});
FIDDLE
I would rather do it by adding newclass on first focus:
$(document).on("focus", ".newText", function() {
if(!$(this).hasClass('focused')){
$(this).addClass('focused')
alert("Great");
}});
Working Demo

Bind close and open function to all dialogs

I try to bind default open and close functions to all dialogs with following ways, however none is working.
$(document).on("dialogopen", ".ui-dialog", function(event, ui) {
});
$(document).on("dialogclose", ".ui-dialog", function(event, ui) {
});
or
$(".ui-dialog").bind("open", function() {
});
$(".ui-dialog").bind("close", function() {
});
Do you have any idea, what is wrong here?
Thanks for your help.
Edit:
I add this function to document ready function.
The following code assumes that all your dialogs container has .ui-dialog-selector class on them. this way you can select all the dialogs.
$(".ui-dialog-selector").bind("dialogopen", function() {
alert('OPen');
});
Similarly you have to bind close
$(".ui-dialog-selector").bind("dialogclose", function() {
alert('Close dialog');
});
UPDATE
JS FIDDLE DEMO
In the demo, you can see, I have 2 dialogs created with div id one and with div id two.
Both these div have classes ui-dialog-selector on it.
<div class ='ui-dialog-selector' id ="one" style="display:none">
<input type="text" value ="open one"/>
</div>
<div class ='ui-dialog-selector' id ="two" style="display:none">
<input type="text" value ="open two"/>
</div>
And then I bind the functions as I have shown above.
for open
$(".ui-dialog").bind("dialogopen", function() {
alert('Open');
});
for close
$(".ui-dialog").bind("dialogclose", function() {
alert('Close');
});

How do I bind to the click event from within the click event when I need to do it repeatedly?

I've got code so that when you click on a word, it is replaced by another word.
<script>
$(document).ready(function() {
$('.note_text').click(function(){
$(this).remove();
$('#note_div').append('<span class="note_text">new</span>');
// re-applying behaviour code here
});
});
</script>
<div id="note_div">
<span class="note_text">preparing</span>
</div>
I need the appended word to have the same click behaviour. What is the best way to do this?
change
$('.note_text').click(function(){
to
$('.note_text').live('click',function(){
This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
You should use a .live()help or .delegate()help binding for that purpose.
$(function() {
$('#note_div').delegate('.note_text', 'click', function(e) {
$(e.target).parent().append("<span class='note_text'>new</span>").end().remove();
});
});
Demo: http://www.jsfiddle.net/PkngP/2/
You could rebind the handler:
function handler(){
$(this).remove();
$('#note_div').append("<span class="note_text">new</span>");
$(".note_text").unbind("click");
$('.note_text').click(handler);
}
$(document).ready(function() {
$('.note_text').click(handler);
});

Categories

Resources