I cannot select li elements after i have added it dynamically - javascript

function appendToSelect_pick_loc1(select, value, content,pSize,i) {
var ulelement=$(select).siblings('.cs-options').children('ul');
$(ulelement).append("<li data-option=\"\" data-value=\""+value+"\"><span>"+content+"</span></li>");
}
The elements are added ,but i cannot select any from them.

To do operations on a dynamically generated element you do not use the simple $(selector).click(function(){}); approach.
To select the dynamically created elements you have to use:
$(document).on('click',selector,function(){
//console.log(this); //the selected item
});
In place of document you can take any element from the DOM that is static (not generated at runtime) and encloses your selector.

Related

Selecting the next input of an event.target

I have (an array of) two inputs product and category.
The product one is an autocomplete.
I would like to fill in the category when a product is selected.
the problem that the event.target is not a jquery object, so it seems I can't apply the jQquery's .next("input")
Here is my code:
var addedProduct = $(".produit:last > input");
addedProduct.autocomplete( {
source: Object.keys(availableProducts),
select: function(event, ui){
var category = event.target.next("input"); // something like this ???
category.value = availableProducts[ui.item.value]; //{"product1":"category1",...}
}
})
The inputs location is like this:
You can create a new jQuery object from the event target with $(event.target). You'll be able to call .next on it afterwards
The other solution without jQuery is to use the native DOM API. You can select the next element with nextElementSibling. The only requirement is that the element you want to target must be immediately the next element.
EDIT: From the DOM structure provided you can use .parent().next() to select the next element at the parent level. Then on this new element use .find() to select the wanted input. Note that the code is highly tied to the DOM structure. You could use the id to directly select the element.
$(event.target).parent().next().find("input");

Assign java scripts to cloned HTML element

I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});

Dynamically adding onchange function to drop down with jQuery

I have a couple of drop down boxes with ids country1, country2, ... When the country is changed in a drop down the value of the country shoudl be displayed in an alert box.
if I add the onchange handler for one box like this it works fine:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
But I need to do this dynamically for all drop down boxes so I tried:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
This doesn't work. No syntax error but just nothing happens when the seleted country is changed. I am sure that the each loop is performed a couple of times and the array contains the select boxes.
Any idea on that?
Thanks,
Paul
The reason .live() existed was to account for elements not present when you call the selector.
$('[id^=country]') .each(function(key,element){ iterates over elements that have an id that starts with country, but only those that exist when you run the selector. It won't work for elements that you create after you call .each(), so using .live() wouldn't do you much good.
Use the new style event delegation syntax with that selector and it should work:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Replace document with the closest parent that doesn't get dynamically generated.
Also, consider adding a class to those elements along with the id attribute.
Instead of incremental ids I'd use a class. Then the live method is deprecated but you may use on with delegation on the closest static parent or on document otherwise.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
You don't need an each loop this way; plus events are attached to all the elements in the jQuery collection, in this case all .country elements.

Jquery get id or class from dynamic element

Let say I have 5 element from PHP query (so it is dynamic)
Illustrated below:
element 1 class=element id=id_1
element 2 class=element id=id_2
element 3 class=element id=id_3
element 4 class=element id=id_4
element 5 class=element id=id_5
We ussulay use jquery event by knowing their class or id, but in this case, we don't know exactly their id.
$("#id_3").click(function()
{
//in this case we have known we want to add event when we click id_3
});
How to deal with dynamic element from PHP query?
For example, how can we know that we click on element 3 with id_3?
What must we fill in $(????).click();?
When I use class, how can I know which id I reference from the class clicked?
This was the only way I could get it to work. For example, if you wanted to get the attribute ID or the value of the element that has been clicked...
$("containerElem").on("click", "someElemID", function(evt) {
var getElemID = $(evt.target).attr("id");
var getVal = $(evt.target).val();
});
In your example the elements all have the same class, so you can setup your event handler based on that:
$(".element").click(function() {
// "this" refers to the clicked element
// this.id will be the id of the clicked element
});
Or if these elements are dynamic in the sense of being loaded via Ajax at some point after the initial page load use a delegated event handler:
$("somecontainerelement").on("click", ".element", function() {
// do something with this.id
});
Where "somecontainerelement" would ideally be the element that the dynamic elements are added to, but could just be document.
If they all have the same class, then you can use a class selector. Then use this to find whatever property you are after.
$('.element').click(
$(this).prop('id');
);
If you want to add a click only then why not add that to the generated html on server side?
You can use attribute starsWith selector & on to bind events on dynamically created elements.
$('body').on('click', '[id^=id]', function(e){
});
This is veryusefull when we work on unknown elements with id or class
$( document ).ready(function() {
// user this if element is div
$('div[id^="id_"]').on('click', function() {
alert($(this).attr('id'));
});
// user this if element is input
$('input[id^="id_"]').on('click', function() {
alert(this.id);
});
});

Jquery get image HTML

How can I copy the whole <img /> using jquery.
At the moment I am trying: $('img').clone().html()
Usage:
'<div class="content-left">'+$(this).find(".bar .info").html()+$(this).find(".bar img").clone().html()+'</div>';
To create new copies of every image in the DOM you can select them and clone them, then append them to some container.
//store a clone of all the images in the DOM in a variable
var $clone = $('img').clone();
//now add the clones to the DOM
$('#newContainer').html($clone);
Here is a demo: http://jsfiddle.net/jasper/r3RDx/1/
Update
You can create your HTML like this:
//create a new element to add to the DOM
//start by creating a `<div>` element with the `.content-left` class
//then add a string of HTML to this element
//then append a set of DOM elements (clones) to the same parent element (the `<div>`)
var $newElement = $('<div />').addClass('content-left').html($(this).find('.bar .info').html()).append($(this).find('.bar img').clone());
//then you can add the new element(s) to the DOM
$newElement.appendTo('#newContainer');
Here is a demo: http://jsfiddle.net/jasper/r3RDx/2/
jQuery objects are simple arrays containing the html of the selected element. This means that I can simply do: $('img.someclass')[0] to access the html of the first (and probably only) matched element.
clone includes the event handlers of the object. If you want just the html whats below would be fine
$('#someid').html($('img'))

Categories