Ajax function doesn't work with dynamic div - javascript

My function for onclick is:
$(document).ready(function() {
$('.mydata').click(function() {
alert($(this).attr('data'));
});
});​
A static element will work:
<div><span id='moreinfo' class='mydata' data="25">Click Me!</span></div>
<div><span id='moreinfo' class='mydata' data="250">Click Me Too!</span></div>
But a div pair populated with the same elements dynamically will not fire off the function. What am I doing wrong?
Code example at: http://jsfiddle.net/KubXr/

you need event delegation:
$(function(){
$(document).on('click', '.mydata', function() {
alert($(this).attr('data'));
});
});
this means that, any element, existing or future, dynamically added, will have the event triggered if contains the mydata class.

Related

How can I get children DIV class name by clicking that div with jQuery

how can it be achieved that when a div is clicked and value is changed, that div class name to be saved to another variable?
Here is the code.
<div id="tradicionalen" contenteditable="true">
<div class="tradicionalen-0">0.1</div>
<div class="tradicionalen-1">0.5</div>
<div class="tradicionalen-2">1.1</div>
<div class="tradicionalen-3">1.7</div>
<div class="tradicionalen-4">2.8</div>
<div class="tradicionalen-5">4.4</div>
<div class="tradicionalen-6">5</div>
</div>
I tried:
$("#tradicionalen").children().click(function(){
alert($(this).attr("class"));
});
and
$("#tradicionalen").find("div").click(function(){
alert($(this).attr("class"));
});
and
$("#tradicionalen div").click(function(){
alert($(this).attr("class"));
});
and still no luck.
I'm using this so I can save the table for later use.
Thanks!
What you've pasted above should work:
var savedVariable;
$("#tradicionalen div").click(function(){
savedVariable = $(this).attr("class");
console.log('Updated: ' + savedVariable);
});
Demo: http://jsbin.com/biwako/1/edit
You can also use delegated events:
$("#tradicionalen").on("click", "div", function () {
console.log($(this).attr("class"));
});
Doing it like this attaches one event handler to the #tradicionalen element. When any div inside #tradicionalen is clicked, the event bubbles upwards until it is caught by the handler, which passes it on to the appropriate callback function.

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

add event for sub children in jquery

Just a little help for me here with jquery.
This is my problem. I have a list
<ul>
<li>
<p>Name</p>
Delete
</li>
</ul>
the 'Delete' event click was initiation in jquery when load page. So the issue now, i'd like to add an element <li></li> which contain children like above. I used jquery to create the tag 'li' contain children, then 'prepend' to the 'ul'.
The problem is, i can not call 'delete' event on new item. Somebody help me please
try this DEMO
var contentToAdd = ' <li> <p>Name</p> Delete </li>';
$('ul').prepend(contentToAdd);
$('ul').on('click','a', function(){
alert('click');
});
The problem is that you're most probably using .click or bind('click') to attach the click event handler to the element. This is fine if all of the elements exist at the time when you attach the event, if however you create new elements that match that same selector, they will not get that event attached.
You need to use the delegate() or .on() method to attach the event to all elements that are current on the page or are appended to the page after they're set up.
An example of a delegate that catches the click event and appends a new element that you can click and see that the same event is attached to each new part of the DOM that matches the selector.
$('#list').delegate('a','click',function() {
alert('Click event fired - Adding a new element to test!');
$('ul').append('<li><p>Name</p>Delete</li>');
return false;
});
Or using the newer .on method:
$('#list').on('click','a',function() {
alert('Click event fired - Adding a new element to test!');
$('ul').append('<li><p>Name</p>Delete</li>');
return false;
});
$('#list') is what my example uses to denote the <ul>, but you could just as easily use $('ul') if you don't want to put an id or class on the list.
Example Fiddle
take a look at this jQuery example:
(one of the last examples on http://api.jquery.com/on/)
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
var count = 0;
$("body").on("click", "p", function(){
$(this).after("<p>Another paragraph! "+(++count)+"</p>");
});
</script>
</body>
</html>
which means in your case you need something like:
$("ul").on("click", "a", function(e){
// delete logic goes here
})
Add the click listener on the UL rather than the a's themselves. This way it will automatically detect clicks to newly added items as well.
$(document).ready(function() {
$("ul").on("click li > a", function() {
$(this).closest("li").remove();
});
});
You can use the .on() method to do so,
The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object
$(document).on("click", "ul li a"), function(){
//your code here
});
Test Link
You can try this,
$("ul").on("click", "a", function(e){
e.preventDefault();
$(this).closest('li').remove();
});
Okay, given that ".on" doesn't meet your requirements, perhaps something like:
$element = $('<li><p>Name</p>Delete</li>');
$element.find("a").click(function(){
//call your delete function
})
$("ul").prepend($element);
Why dont you use jquery templating.
You can define a text/template and iterate over it to get your desired result.
an example:
**THIS IS YOUR SCRIPT**
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> was released in ${ReleaseYear}.</li>
</script>
**THIS IS THE JQUERY TEMPLATE**
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
**THIS IS YOUR HTML**
<ul id="movieList"></ul>
More examples :
http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/

Jquery append input element and send data from that input element

I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});​
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});​
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
​
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/

How do I bind to the click event from within the click event when I need to do it repeatedly?

I've got code so that when you click on a word, it is replaced by another word.
<script>
$(document).ready(function() {
$('.note_text').click(function(){
$(this).remove();
$('#note_div').append('<span class="note_text">new</span>');
// re-applying behaviour code here
});
});
</script>
<div id="note_div">
<span class="note_text">preparing</span>
</div>
I need the appended word to have the same click behaviour. What is the best way to do this?
change
$('.note_text').click(function(){
to
$('.note_text').live('click',function(){
This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
You should use a .live()help or .delegate()help binding for that purpose.
$(function() {
$('#note_div').delegate('.note_text', 'click', function(e) {
$(e.target).parent().append("<span class='note_text'>new</span>").end().remove();
});
});
Demo: http://www.jsfiddle.net/PkngP/2/
You could rebind the handler:
function handler(){
$(this).remove();
$('#note_div').append("<span class="note_text">new</span>");
$(".note_text").unbind("click");
$('.note_text').click(handler);
}
$(document).ready(function() {
$('.note_text').click(handler);
});

Categories

Resources