I'm trying to dynamically add an event listener to a select box.
With this code I just don't get any response, so no alert box:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
$("sel1").on('change', function() {
alert(this.val());
});
table.append(row);
$('#mydiv').append(table);
Also, how can I add the select box between the td?
Currently, it's added between the tr, td simply isn't there.
Here is a fiddle
Updated Fiddle
You should use event delegation on() when you deal with fresh DOM added dynamically :
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
NOTES :
You should add id selector before sel1 it should be #sel1.
.val() is a jquery method you can't call it on javascript object like this.val() it should be $(this).val().
The current code will not add select inside td it will add it directely inside tr tag so you could replace :
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option>
<option>test2</option></select>');
By :
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>
test2</option></select></td>');
Hope this helps.
Working Snippet
var table = $('<table></table>');
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
table.append(row);
$('#mydiv').append(table);
td{
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
Couple of points to note in your code
1) Wrong Selector $("sel1")
The problem in your code is $("sel1") you need to select by id using # so it should be $("#sel1"). So your code would be like
$("#sel1").on('change', function() {
alert(this.val());
});
2) Bind event after appending the HTML to DOM or Use Event Delegation
Your code should be places in this order Working Fiddle
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);// now the element is added to DOM so bind event
$("#sel1").on('change', function() {
alert($(this).val()); // note here I changes this.val() to $(this).val()
});
Or another option is using event delegation Working Fiddle
To add event's to dynamic elements use the event delegation
$('body').on('change',"#sel1", function() {
alert($(this).val());
});
3) To place the select tag inside td use the below syntax
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
Wrap the td along with the select tag and not inside the tr Working Fiddle
You need to bind the change event after appending to the page:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);
$("#sel1").on('change', function() {
alert(this.val());
});
And also you have forgotten the # id selector for "sel1"
There are three major issues in your code
1.The id selector must start with #
$("#sel1").on('change', function() {
2.You should bind the change listener only after you appended the element, because it just doesn't exist in the DOM before
3.With
$('<tr><td></td></tr>')
you'll get a jquery reference to the row (the <tr> element). Then with .html() you are replacing the content of the row (including the <td> of course)
Here I have a problem:
I created one div and passed some data into it:
var div = $("<div />");
$.data(div, "a", 1);
div.on("click", function(event) {
console.log($.data(event.target, "a")); // print undefined
});
It looks like I could not retrieve data bound with an UI element this way. I would like to know why and whether there is any alternative for this - get a piece of data associated with an UI element within an event.
Thanks!
Try this ;-)
var div = $("<div>clic</div>").appendTo('body');
div.data("a", 1);
div.on("click", function() {
console.log($(this).data("a"));
});
JsFiddle : http://jsfiddle.net/t3n8y2xz/
I didn't expect it but the following test fails on the cloned value check:
test("clone should retain values of select", function() {
var select = $("<select>").append($("<option>")
.val("1"))
.append($("<option>")
.val("2"));
$(select).val("2");
equals($(select).find("option:selected").val(), "2", "expect 2");
var clone = $(select).clone();
equals($(clone).find("option:selected").val(), "2", "expect 2");
});
Is this right?
After further research I found this ticket in the JQuery bug tracker system which explains the bug and provides a work around. Apparently, it is too expensive to clone the select values so they won't fix it.
https://bugs.jquery.com/ticket/1294
My use of the clone method was in a generic method where anything might be cloned so I'm not sure when or if there will be a select to set the value on. So I added the following:
var selects = $(cloneSourceId).find("select");
$(selects).each(function(i) {
var select = this;
$(clone).find("select").eq(i).val($(select).val());
});
Here's a fixed version of the clone method for jQuery:
https://github.com/spencertipping/jquery.fix.clone
// Textarea and select clone() bug workaround | Spencer Tipping
// Licensed under the terms of the MIT source code license
// Motivation.
// jQuery's clone() method works in most cases, but it fails to copy the value of textareas and select elements. This patch replaces jQuery's clone() method with a wrapper that fills in the
// values after the fact.
// An interesting error case submitted by Piotr Przybył: If two <select> options had the same value, the clone() method would select the wrong one in the cloned box. The fix, suggested by Piotr
// and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val().
(function (original) {
jQuery.fn.clone = function () {
var result = original.apply(this, arguments),
my_textareas = this.find('textarea').add(this.filter('textarea')),
result_textareas = result.find('textarea').add(result.filter('textarea')),
my_selects = this.find('select').add(this.filter('select')),
result_selects = result.find('select').add(result.filter('select'));
for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
return result;
};
}) (jQuery.fn.clone);
Made a plugin out of chief7's answer:
(function($,undefined) {
$.fn.cloneSelects = function(withDataAndEvents, deepWithDataAndEvents) {
var $clone = this.clone(withDataAndEvents, deepWithDataAndEvents);
var $origSelects = $('select', this);
var $clonedSelects = $('select', $clone);
$origSelects.each(function(i) {
$clonedSelects.eq(i).val($(this).val());
});
return $clone;
}
})(jQuery);
Only tested it briefly, but it seems to work.
My approach is a little different.
Instead of modifying selects during cloning, I'm just watching every select on page for change event, and then, if value is changed I add needed selected attribute to selected <option> so it becomes <option selected="selected">. As selection is now marked in <option>'s markup, it will be passed when you'll .clone() it.
The only code you need:
//when ANY select on page changes its value
$(document).on("change", "select", function(){
var val = $(this).val(); //get new value
//find selected option
$("option", this).removeAttr("selected").filter(function(){
return $(this).attr("value") == val;
}).first().attr("selected", "selected"); //add selected attribute to selected option
});
And now, you can copy select any way you want and it'll have it's value copied too.
$("#my-select").clone(); //will have selected value copied
I think this solution is less custom so you don't need to worry if your code will break if you'll modify something later.
If you don't want it to be applied to every select on page, you can change selector on the first line like:
$(document).on("change", "select.select-to-watch", function(){
Simplification of chief7's answer:
var cloned_form = original_form.clone()
original_form.find('select').each(function(i) {
cloned_form.find('select').eq(i).val($(this).val())
})
Again, here's the jQuery ticket: http://bugs.jquery.com/ticket/1294
Yes. This is because the 'selected' property of a 'select' DOM node differs from the 'selected' attribute of the options. jQuery does not modify the options' attributes in any way.
Try this instead:
$('option', select).get(1).setAttribute('selected', 'selected');
// starting from 0 ^
If you're really interested in how the val function works, you may want to examine
alert($.fn.val)
Cloning a <select> does not copy the value= property on <option>s. So Mark's plugin does not work in all cases.
To fix, do this before cloning the <select> values:
var $origOpts = $('option', this);
var $clonedOpts = $('option', $clone);
$origOpts.each(function(i) {
$clonedOpts.eq(i).val($(this).val());
});
A different way to clone which <select> option is selected, in jQuery 1.6.1+...
// instead of:
$clonedSelects.eq(i).val($(this).val());
// use this:
$clonedSelects.eq(i).prop('selectedIndex', $(this).prop('selectedIndex'));
The latter allows you to set the <option> values after setting the selectedIndex.
$(document).on("change", "select", function(){
original = $("#original");
clone = $(original.clone());
clone.find("select").val(original.find("select").val());
});
If you just need the value of the select, to serialize the form or something like it, this works for me:
$clonedForm.find('theselect').val($origForm.find('theselect').val());
After 1 hour of trying different solutions that didn't work, I did create this simple solution
$clonedItem.find('select option').removeAttr('selected');
$clonedItem.find('select option[value="' + $originaItem.find('select').val() + '"]').attr('selected', 'true');
#pie6k show an good idea.
It solved my problem. I change it a little small:
$(document).on("change", "select", function(){
var val = $(this).val();
$(this).find("option[value=" + val + "]").attr("selected",true);
});
just reporting back. For some godly unknown reason, and even though this was the first thing I tested, and I haven't changed my code whatsoever, now the
$("#selectTipoIntervencion1").val($("#selectTipoIntervencion0").val());
approach is working. I have no idea why or if it will stop working again as soon as I change something, but I'm gonna go with this for now. Thanks everybody for the help!
So I have EDIT and REMOVE buttons that are dynamically added for each data node (a "poll") in a Firebase database. I have a function which assigns onclick listeners to these with jQuery, but oddly, the event only fires when there just happens to be a single node, and hence a single pair of EDIT/REMOVE buttons. When there are multiple nodes and multiple pairs of buttons, none will fire. Here's the javascript where the events are added to the buttons...
function displayCurrentPollsForEditing(pollsRef)
{
var tbl = createTable();
var th = ('<th>Polls</th>');
$(th).attr('colspan', '3');
$(th).appendTo($(tbl).children('thead'));
pollsRef.once('value', function(pollsSnapshot) {
pollsSnapshot.forEach(function(pollsChild) {
var type = pollsChild.name();
// If this is true if means we have a poll node
if ($.trim(type) !== "NumPolls")
{
// Create variables
var pollRef = pollsRef.child(type);
var pollName = pollsChild.val().Name;
var btnEditPoll = $('<button>EDIT</button>');
var btnRemovePoll = $('<button>REMOVE</button>');
var tr = $('<tr></tr>');
var voterColumn = $('<td></td>');
var editColumn = $('<td></td>');
var rmvColumn = $('<td></td>');
// Append text and set attributes and listeners
$(voterColumn).text(pollName);
$(voterColumn).attr('width', '300px');
$(btnEditPoll).attr({
'class': 'formee-table-button',
'font-size': '1.0em'
});
$(btnRemovePoll).attr({
'class': 'formee-table-remove-button',
'font-size': '1.0em'
});
$(btnEditPoll).appendTo($(editColumn));
$(btnRemovePoll).appendTo($(rmvColumn));
// Append to row and row to table body
$(tr).append(voterColumn).append(editColumn).append(rmvColumn);
$(tr).appendTo($(tbl).children('tbody'));
// Append table to div to be displayed
$('div#divEditPoll fieldset#selectPoll div#appendPolls').empty();
$(tbl).appendTo('div#divEditPoll fieldset#selectPoll div#appendPolls');
$(btnEditPoll).click(function() {
displayPollEditOptions(pollRef);
return false;
});
$(btnRemovePoll).click(function() {
deletePoll($(this), pollsRef);
return false;
});
}
});
});
}
The markup would be something like the following...
<div id="divEditPoll">
<form class="formee" action="">
<fieldset id="selectPoll">
<legend>SELECT A POLL</legend>
<div class="formee-msg-success">
</div>
<div class="grid-12-12" id="appendPolls">
</div>
</fieldset>
</div>
EDIT - So I've switched some lines around and now I don't set the click() events until the buttons are appended to the document, so the button elements are definitely in the DOM when the click events are attached. So could this issue result from not setting id's for these buttons? That seems strange to me, since I'm using variable references rather than ids to attach the events.
There are two things I would check for.
First, make sure you don't have two elements with the same id. If you do, jquery may only bind to the first, or not bind at all.
Second, make sure the element is added to the dom before jquery attempts to bind the click event. If the code is running asynchronously, which can easily happen if you're using ajax, then you may be trying to bind the event before creating the element. Jquery would fail to find the element then give up silently.
you should use .on() for dynamically added button
How come this doesn't work (operating on an empty select list <select id="requestTypes"></select>
$(function() {
$.getJSON("/RequestX/GetRequestTypes/", showRequestTypes);
}
);
function showRequestTypes(data, textStatus) {
$.each(data,
function() {
var option = new Option(this.RequestTypeName, this.RequestTypeID);
// Use Jquery to get select list element
var dropdownList = $("#requestTypes");
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
}
);
}
But this does:
Replace:
var dropdownList = $("#requestTypes");
With plain old javascript:
var dropdownList = document.getElementById("requestTypes");
$("#requestTypes") returns a jQuery object that contains all the selected elements. You are attempting to call the add() method of an individual element, but instead you are calling the add() method of the jQuery object, which does something very different.
In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using $("#requestTypes")[0].
By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned:
var dropdownList = $("#requestTypes")[0];
For stuff like this, I use texotela's select box plugin with its simple ajaxAddOption function.