Not able to add datepicker to new element - javascript

I'm dynamically adding new form elements using jquery. For some reason, a call to .datepicker() won't work on the new elements I add, but did work on the old ones that were not added dynamically. If I put .attr('style', 'color: red;')
instead of .datepicker(), it works. Note that the original call inside of the document ready function works.
This is the code that gets called when the add button is clicked:
function addMulti(name) {
it = $('[name=' + name + ']');
base = it.data('baseName');
on = it.data('number') + 1;
name = base + "-" + on;
copy = it.clone()
copy.prop("name", name).attr("data-is-default", false).removeAttr('data-number').
fadeIn('slow').appendTo(it.parent());
it.data('number', on);
if(it.hasClass('date-pickable')) { // <-- This returns true, I checked.
copy.datepicker();
// Where if I add clone.attr('style', 'color: red;') it turns it red.
}
}
This is the call that makes all of the fields that are created at that point date pickers:
<script type="text/javascript">
$(document).ready(function() {
$("input.date-pickable").datepicker()
});
</script>
There are no errors that show up in firebug or the google chrome "inspect element" thing. Something odd is happening though. If I type in the same call as in the document.ready function into the firebug consul, it still won't make the newly added elements datepickers. Yet if I hover over the output, it selects the elements that it should be targeting.
$("input.date-pickable").datepicker() // What I typed in
Object[input#dp1371953134342.field-input 06/22/2013, input#dp1371953134343.field-input, input#dp1371953134342.field-input 06/22/2013, input#dp1371953134342.field-input 06/22/2013] // What it put out. The last three numbers are the IDs JQuery assigned to the added elements. I checked.

jQuery UI's datepicker will always add the class hasDatepicker to any element that has a datepicker to avoid attaching multiple datepickers to the same element.
When you're cloning an element that already has a datepicker, you get that class as well, and you can't attach a new datepicker to the clone, as jQuery UI thinks the element already has a datepicker.
Remove the class from the clone:
var copy = it.clone(false);
copy.removeClass('hasDatepicker').prop("name", name)
.attr("data-is-default", "false").removeAttr('data-number')
.fadeIn('slow').appendTo(it.parent());
and try not to make all your variables global.

Will this work?
<script type="text/javascript">
$(document).ready(function() {
$(document).on('focus',"input.date-pickable", function(){
$(this).datepicker();
});
});
</script>
Demo JSfiddle

Related

Chosen JS with clone(true,true), rerender on append

I am using the Chosen JS jQuery plugin & I am trying to get it to rerender every time a cloned element (using true, ture - this is because I need to copy the on click events) is appended to the dom.
This is my code:
var container = jQuery(self.options.parent_class + ' tbody tr:first-child'),
container_clone = container.clone(true,true);
var elem = container_clone.find('select');
elem.chosen('destroy');
elem.chosen();
return container_clone;
Here it is on fiddle: http://jsfiddle.net/udj7t/1/
Try this,
$(document).ready(function(){
$('select').chosen();
$('a#clone_me').on('click', function(){
var $clone = jQuery('#toClone select:first').clone();
$clone.removeAttr('style');
//$clone.chosen('destroy');
jQuery('#toClone').append($clone);
jQuery('#toClone select:last').chosen();
});
});
Demo
For those interested in a possible solution that will work with clone(true, true), as per the OP's actual question I found that doing the following worked for me. I also had multiple selects in my cloned row so I needed to use the each() method. This could easily be adapted though.
// Look through the cloned row and find each select
$clone.find('select').each(function (){
// Because chosen is a bitch with deep cloned events
// We need to make another internal clone with no events
$clonedChosen = $(this).clone().off();
// Now we can delete the original select box
// AND delete the chosen elements and events
// THEN add the new raw select box back to the TD
$parentTd = $(this).closest('td');
$parentTd.empty().append($($clonedChosen).show());
// Finally, we can initialize this new chosen select
$parentTd.find('select').chosen();
}

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});

jQuery: Running multiple datepicker's on dynamically created inputs

I am trying and failing to add datepicker to inputs that are created dynamically.
They have different id's and I am specifically targeting the new input and calling datepicker.
In the jsFiddle example below it only works for the 2nd input (first one datepicker is called on) and does not work for any others after that.
Here is the jsFiddle: http://jsfiddle.net/TJfbc/1/ Press the plus sign to add more.
Note: I am aware the first element will not have the datepicker.
Here's a cleaner alternative
$(function() {
//append one handler to the parent to detect append actions
$('.action_items').on('click', '.expand', function() {
var $el = $(this);
$el.parent()
.clone()
.appendTo($el.closest('.action_items'))
.find('input')
.removeClass('hasDatepicker')
.each(function () {
newName = this.name.slice(0,6) + (parseInt(this.name.slice(6)) + 1);
this.name = newName;
this.id = newName;
})
.datepicker();
//change text, remove original handler, add the remove handler
$el.text('-').off('click').on('click',function(){
$(this).parent().remove();
});
})
});​
http://jsfiddle.net/TJfbc/27/
You need to "refresh" the previous textfield that has already class of 'hasDatepicker' before you can initialize a new one
new_action_item.find('.dpDate').removeClass('hasDatepicker').datepicker()
An improvement on readability:
No need to repeatedly call $() on new_action_item since clone() returns an already jQuery object

getting individual atrributes while selecting a class with JQuery

I'm new to javascript and JQuery, and I'm working in a small project with JSP.
I create a grid dynamically with JSP and I added some buttons wich class is "select" and in the alt attribute I set the current row index. That works perfectly, I'm trying to set the onclick dynamically. This is my code
$('.select').click(function (){
alert($('.select').attr('alt'));
}
I want to each button to show its own index, but that code shows just the first index in each button. I've searched how to do it, but nothing comes out.
Is there a chance to do what I want?
change this line as:
alert($(this).attr('alt'));
When jQuery calls your event handler it sets this to be the DOM element in question, so try this:
$('.select').click(function (){
alert($(this).attr('alt'));
});
If you need to access DOM element properties you can then get them directly, e.g.:
alert( this.id );
this.value = "test";
If you need to use jQuery methods on the element you need to pass it to the jQuery function first, e.g.:
$(this).hide();
$(this).css("color","red").slideDown();
$('.select').click(function (){
alert($(this).attr('alt'));
});
Change
alert($('.select').attr('alt'));
by
alert($(this).attr('alt'));
Now you select the attr alt of the button lauch the event.
Not sure if that's what you're looking for but...
$('.select').click(function() {
$('.select').each(function() {
$(this).attr('value', $(this).attr('alt'));
});
});
This'll have every button "show" the value stored within their alt attribute when you click one button.
By the way, if you're using 1 button per row, you'd probably better go with index().

JQuery Get current ID of Widget

I have have the following
<div id="dualList"></div>
And I have written a plugin but for the sake of testing I have stripped it away. I am having problems with the plugin displaying the id of the div.
<script>
(function($) {
$.fn.DualList = function() {
var thisControl = $(this);
alert(thisControl.attr('id'));
}
})(jQuery);
</script>
And its bound on document on ready using
$("#dualList").DualList();
Any ideas why the ID isnt echoing out?
First off, as far as I can tell, it does work.
However, there are a couple of things that are not optimal in your code. You can't be sure that there's just one onject selected (it could be a class selector, for all you know). You should therefore iterate through all the members of the selection. Second, you don't need the jQuery constructor to get the id property. You can do it just with this.id:
$.fn.DualList = function() {
return this.each(function() {
alert (this.id);
});
};
Working example of this style of code
Widget is a collection wherever invoked, so
$(this.element[0]).attr("id")
will get you the id of the first element and so on..

Categories

Resources