I'm using jQuery 1.9.0 and I'm trying to trigger the on() method whenever an option is changed inside a select. It worked with live() but I think its probably something simple that I'm not seeing.
This is my HTML:
<select class="select_exercise">
<option class="option_exercise">Example 1</option>
<option class="option_exercise">Example 2</option>
</select>
and my Script:
$("option.option_exercise").on("change","option.option_exercise",function()
{
alert("i am changing");
});
Here is the fiddle
The .on() method lets you delegate an event handler higher up the DOM tree. The idea is that you bind an event handler to an ancestor element, but only execute that handler when the event that has reached it originated on a descendant element matching the selector.
In your case, that would be this:
$(".select_exercise").on("change", ".option_exercise", function () {
// ^---- Probably no need to qualify the selectors with a tag name
alert("i am changing");
});
However, given your example code, this will not work since option elements will never fire change events (the select element will though). Assuming the select element is in the DOM from the time it loads, you can bind directly to it:
$(".select_exercise").on("change", function () {
alert("i am changing");
});
And if it's not in the DOM initially, you'll have to delegate higher (I'm using body here as an example. You should try and delegate to the closest possible ancestory that will be in the DOM at load):
$("body").on("change", ".select_exercise", function () {
alert("i am changing");
});
$("option.option_exercise").on("change","option.option_exercise" should be $("select.select_exercise").on("change",function()
Demo: Fiddle
You could try to do the following.
$(".select_exercise").change(function()
{
alert("i am changing");
});
you can use
$('.select_exercise').change(function() {
alert('Handler for .change() called.');
});
Ok
You need to check if the select element has been changed and not one of the option.
In this example i am checking if the select element which has a class called "select_exercise" has been changed.
And i am gessing you want to get the selected option so look at this code
$(".select_exercise").on("change",function()
{
alert($(this).find(":selected").text()); --Get the selected option text
alert("i am changing");
});
Fiddle Example
This works fine:
$("select.select_exercise").on("change", function () {
alert("i am changing");
});
The select is what changes, not the option, because it's the value of the select that changes, not the options.
Related
I am trying to get option value on hover/mouseover event when option is hovered using chosen plugin....
Fiddle : Demo Fiddle
Here is js code...
$("#myselect").chosen();
$('#myselect').next('.chosen-container').on('mouseenter', 'li.active-result', function(e) {
alert($(this).text());
alert($(this).val()); // how to get option value...?
});
USe delegate for that, because chosen plugin creates the .active-result class elements dynamically.
$("#myselect").chosen();
$(document).on("hover",".active-result",function(){
alert($(this).text());
});
Fiddle
Edit
$(document).on("hover",".active-result",function(){
alert($("#myselect option").eq($(this).data("option-array-index")).val());
});
Updated fiddle
You need event delegation for binding the events to dynamically added DOM:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$("body").on('mouseenter','li.active-result',function(){
alert($(this).data('option-array-index'));
});
Working Demo
As this plugin created new elements for options and to read option value you need find option matching text and read its value:
$('#myselect').next('.chosen-container').on('mouseenter', 'li.active-result', function(e) {
var currentText = $(this).text();
alert($(this).text());
alert($('#myselect option').filter(function () { return $(this).html() == currentText; }).val()); // how to get option value...?
});
Demo
This is the fiddle for the issue:
http://jsfiddle.net/PdA4W/4/
Alert is empty (no value), when the select changes.
This is, I think because I have this line:
$(document).on('change', '.variant', function()
Now I cannot do it differently, according to my previous question:
Appended select with jQuery, delegate/on event not working
I need to do it this way, because that I am cloning the variant div element each time you press Add
So how can I obtain the current selected option value in the select that are changing?
Change
$(document).on('change', '.variant', function(){
to
$(document).on('change', '.quantity', function(){
DIV doesn't listen to jQuery's 'change' event in the way you're thinking; only SELECT elements (and I think a couple other elements) do. Is that what you're looking for?
You are trying to add a change handler to a <div> not <select>
Modify the selector to target the <select>
$(document).on('change', '.variant select.quantity', function(){
alert( $(this).val() );
});
DEMO
The change is in quantity. Look here: http://jsfiddle.net/JY3fC/
$(function(){
$('.add_variant').on('click', function(){
var $orig = $('.variants div:first').clone();
$('.variants').append($orig);
});
$(document).on('change', '.quantity', function(){
alert( $(this).val() );
});
});
I have a dialog with a
<ul id="suggestions0">
<li id="suggestion0-0" class="suggestion">BLO</li>
<li id="suggestion0-1" class="suggestion">BLU</li>
<li id="suggestion0-2" class="suggestion">BLL</li>
<li id="suggestion0-3" class="suggestion">BOO</li>
<li id="suggestion0-4" class="suggestion">CLA</li>
</ul>
that I want to replace the content dynamically.
I change to ul content with this
$("#suggestions0").html("<li id='test0-1' class='suggestion'>BLO</li><li id='test0-2' class='suggestion'>BLO</li><li id='test0-3' class='suggestion'>BLO</li><li id='test0-4' class='suggestion'>BLO</li><li id='test0-5' class='suggestion'>BLO</li><li id='test0-6' class='suggestion'>BLO</li>");
What I want is when I click on one of these word, I want to do something, suppose an alert.
I try to do this
$(".suggestion").on("click", function() {
alert(this.id);
});
but the alert never appear.
here a sample that show the problem
http://jsfiddle.net/survivant/cyFxp/1/
in the sample, if you click on OK, it doesn't change to content, so if you click on a LI, it will works, but if you click on NOTOK, the events won't be received.
I'm using jQuery 1.7+, the live api is deprecated, or removed, it the APi suggest to use on().
You are not using on correctly. live is used to bind event handlers to the document to listen for events that bubble up from a specific selector, but by calling on explicitly on .suggestion, you will only attach the listeners to existing suggestions. So you need to use on to bind on an element that will always exist, and pass a selector to pick out the elements that get created dynamically.
// With live like this:
$('.suggestion').live('click', ...
// Is equivalent to this:
$(document).on('click', '.suggestion', ...
// Not this:
$('.suggestion').on('click', ...
In your case, rather than basing on off document, you can use your ul.
$("#suggestions0").on('click', '.suggestion', function(){
alert(this.id);
});
I found a solution, not sure that is the best one, but seems to work.
$("#suggestions").on("click","li", function() {
alert(this.id);
});
The script below only bind click event to DOMs current exist in the page.
$(".suggestion").on("click", function() {
alert(this.id);
});
To bind click event to all DOMs that are and will be created in the page. Bind the event to the document instead.
$(document).on("click", ".suggestion", function() {
alert(this.id);
});
See fiddler for codes.
Pass a selector to on() and it works like the old live():
$("#suggestions0").on("click", ".suggestion", function () { alert(this.id); });
See updated fiddle: http://jsfiddle.net/cyFxp/2/
suggestions is not a class but an id thus
it should not be
$(".suggestion").on("click", function() {
alert(this.id);
});
But like this
$("#suggestion").on("click", function() {
alert(this.id);
});
That is, instead of a dot you prefix it with a pound sign #.
I was under the impression that jquery's on() reacted to events attached elements dynamically added to the dom (via ajax or cloning, etc). However, the following is only working for the element attached to the dom at page load. The other copy I make of it using clone() is not being, well, handled.
$(document).ready(function () {
$('.ship_via_dropdown').on('change', function () {
console.log($(this));
if ($(this).hasClass('prev_change')) {
console.log('has');
} else {
$(this).addClass('prev_change');
console.log('hasn\'t');
}
});
});
Code for cloning:
$(document).ready(function(){
var form1 = $('.line_item_wrapper').children().clone();
$('#new_line_content_1').html(form1);
});
HTML for dropdown (contents added by jquery db query on document ready)
<span class="select ship_via_select_container">
<select class="ship_via_dropdown ship_via_dropdown_1">
</select>
</span>
Thank you for any insight!
Either delegate the event instead:
$(document).on('change', '.ship_via_dropdown', function () {
console.log($(this));
if ($(this).hasClass('prev_change')) {
console.log('has');
} else {
$(this).addClass('prev_change');
console.log('hasn\'t');
}
});
Or better yet, use .clone(true) to clone with events. (Note: this will only work if you're cloning AFTER the event handler is attached.)
It does, but not in the way that you think. When used as you have used it:
$('.ship_via_dropdown').on('change',
It is really not different than using .change(). What you are looking for is event delegation. This takes the following form:
$("<selector to static ancestor>").on('change', '.ship_via_dropdown', function () {
Where <selector to static ancestor> is a selector to a static ancestor of the dynamically added elements. (one that is not dynamically created) As a last resort document can be used here. However for performance, this should be the closest static ancestor element.
jquery's on() reacted to events attached elements dynamically added
No - or at least, only if you use it with delegated events. The live method did always delegate events to the document.
Change this line:
$('.ship_via_dropdown').on('change', function () {
to this:
$(document).on('change',".ship_via_dropdown", function () {
lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});