jQuery .live('click', function() {}); doesn't work for iPad - javascript

I have some jQuery functions which update some numbers when new values are selected in a <SELECT> field. The <SELECT> items are added dynamically by the user, so these functions use the .live() function. Everything goes as planned in Mozilla, Chrome, and IE8, but when I try to access the page on my iPad the numbers are no longer being updated accordingly. I have to click the <SELECT> field a second time for the numbers to update. Here is one of my functions:
// Update subtotal when .months is changed
$(".months").live('click',function(){
var pid = this.id.replace("months", "");
var price = document.getElementById('row' + pid).className;
updateSubtotal(pid, price);
});
All of the functions are contained within the document.ready() block. I've tried 'click change' and just 'change' as well, but they have issues in some other browsers.
Thanks for any and all help!

iPad and select elements don't play very nice. You will need to bind to blur if you need the selected value to do anything.
Try something like this ( .months should be your select element ):
// Update subtotal when .months is changed
$(".months").on('blur', function(){
var pid = this.id.replace("months", "");
var price = document.getElementById('row' + pid).className;
updateSubtotal(pid, price);
});
EDIT
Try this:
// Update subtotal when .months is changed
$(document).on('blur|click', ".months", function(){
var pid = this.id.replace("months", "");
var price = document.getElementById('row' + pid).className;
updateSubtotal(pid, price);
});
The nice thing about on() is that you can attach it to an element and delegate from there. Since your $(document) will always be there it can also catch elements you add dynamically to the page and which are not there from the beginning. Since your original code used live I
expect the element to by loaded or generated dynamically. In that case in order to bind an event to it using on() you have to bind to the document and delegate to whatever .months is coming.

If you add an empty onclick="" to the div (or span, or anything), it works....
I dont't know why :)

Related

get id and value dynamically created element jquery

I need the id(and other attributes such as value) of a span i previously created on an ajax event.
Is there a way to do this?
This is how the span is created on php post:
echo "<span class='non-skin-symptom-choice disease_option' ".
"onclick='showinfo(".$var[0].");' id=".$var[0].">"
.$var[1]." -- ".number_format($var[3]*100, 2, '.', '')."%</span>";
and I want to get its id whenever a checkbox is clicked.
$(".chb").click(function(){
var id= $(this).attr('id');
var list=[];
$('.disease_option').each(function (){
alert("this.val=="+ $(this).attr("val")); //i need the value here
var str= $(this).attr("value").split(" -- ")[1];
alert(str);
str=str.slice(0,str.length - 1);
if(parseFloat(str) >=support)
list.push(id) //i need the id here
});
the checkbox is not dynamically created, so $(".chb").click(function(){} works.
somehow, $(this).attr("id") works but $(this).attr("val") returns undefined... i also tried $(this).attr("value") but same results. $(this).val returns empty.
use
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
as this have a high level event attachment and it can get the elements who have been created on a runtime
Try this
alert($(".non-skin-symptom-choice").attr("id"));
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have create a "delegated" binding by using on()
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
possible duplicate: Click event doesn't work on dynamically generated elements
If your DOM node did not exist when the page loaded (ie. it was added to the page via AJAX after the page loaded), jQuery cannot see it if you try to update it or read it with jQuery methods. One way to overcome this is to set up your jQuery function to reference the class or ID of the parent of the node you want to target (assuming the parent class is loaded into the page on page load), along with the class of the node you want to target. For example:
$(".chb").click(function(){
var id = $(".your-parent-class .non-skin-symptom-choice").attr("id");
}
}

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();
}

Not able to add datepicker to new element

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

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

jQuery .click() event for multiple div's

I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()

Categories

Resources