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");
}
}
Related
I have a div with a class .display_noti and inside it I have append another div with class .palnotific by jquery.I have fetched data from database and i converted that fetched data into json_encode.I used that json format data and made some information which were append on that div with class .palnotific.
my first jquery code which append data inside that div with class .display_noti looks like :-
$.getJSON("notification.php",function(data){
// you can do checking here
if ( data.result && data.result.length > 0 ) {
$(".display_noti").empty(); // Clear out the div
$.each(data.result,function(){
$(".display_noti").append("<div class='palnotific'>You got a pal requet from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+this['pals_id']+"'></form></div>");
});
done();
}
else {
$(".display_noti").append("<div class='palnotific' style='background-color:white;'>You have no notification to view.</div>");
}
Above I first get the json format data and I did some validation and then at last I append that second div with class .palnotific inside that first div with a class .display_noti.I have a form inside that append div which I use to take value from a input for use.
As we know .palnotific is an appended div.I wanted to use some Onclick event function on it so, I used below code :-
$('body').on('click','.palnotific',function(){
var x = $(this).closest('.display_noti').find('.palid');
var pid=x.val();
$.ajax({
url:'notifipro.php',
type:'post',
data:"palid="+pid,
success: function(data){
if(data==1)
{
$(window).load('oldpage.php');
}
if(data==2)
{
$(window).load('newpage.php');
}
}
});
});
Above code takes the input value from that form which was inside that .palnotific div which was appended from jquery at previous.As you know those appended div carry data from database via json_encode.It will take value as much as available in database which mean if there's 2 data in database json_encode will also have 2 data and those append div class which takes data from json_encode will append 2 time that div with a class palnotific.Now my problem is that if i have two div with class palnotifi origin from that append my click function work for first div only and when i click on second div onclick function doesn't work.No matter I have 2 or more then two div if I click any one div first div click function takes action.How can I make work onclick function to those div only which have been clicked?
The easiest way to have jquery react on an element that is dynamically created, is to attach the event to that element itself. Another way would be using on on a the container div with a subfilter, but since you are already creating the html, you can encapsulate it in $('yourhtml') and attach the click directly to that created element. In combination with appendTo instead of append, you can also chain the append and click:
//mock data:
var data={result: [
{from_user: 'A', notification_date: new Date(), pals_id: 1},
{from_user: 'B', notification_date: new Date(), pals_id: 2},
{from_user: 'C', notification_date: new Date(), pals_id: 3}
]};
$.each(data.result,function(){
var id = this.pals_id;
$("<div class='palnotific'>You got a pal request from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+ id +"'></form></div>")
.appendTo(".display_noti")
.click(function(){
//attach pre existing function or assign your logic here
alert('You clicked ' + id);
})
});
Example fiddle
In this example, the id was also stored before hand and reused inside the attached click. If you need to use the raw value, you can use $(this).find('.palid').val() (as done in this fiddle )
From the code you paste, the problem should be this line:
var pid=x.val();
as you can find in jQuery docs (http://api.jquery.com/val/)
.val() Get the current value of the first element in the set of matched elements or set the value of every matched element.
You can use a more specific CSS3 Selector in the on() function. I'm not entirely sure this is going to solve your overall problem, but it might lead you in the right direction.
$(".display_noti").on("click", ".palnotific:first", function(event) {
console.log("You Clicked: ", event.target.id);
});
Here is an example JSFiddle;
I am simply appending an element that is on the DOM like:
$("#div_element").append('test');
Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:
$("#div_element").append('test').click(function(){alert("test")});
But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.
You can do this:
var el = $('test');
$("#div_element").append(el);
el.click(function(){alert("test")});
// or preferrably:
el.on('click', function(){alert("test")});
The append function accepts two types of arguments: a string or a jQuery element.
In case a string is passed in, it will create a jQuery element internally and append it to the parent element.
In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.
After you've done that, you still have access to the jQuery element to be able to attach the handler.
var $a = $('<a />', {href:"#"})
.text("test")
.on('click', function(e) {
alert('Hello')
})
.appendTo('#div_element');
http://jsfiddle.net/33jX4/
Why not save a reference to the new element before you append it:
var newElement = $('test');
$("#div_element").append(newElement);
newElement.click(function(){alert("test")});
The last element would be the new element
$('a:last','#div_element').on('click',function(){
// do something
});
Add identity to that element then use it as follows
$("#div_element").append('<a id="tester" href="#">test</a>');
$('#tester').on('click', function(event) {
console.log('tester clicked');
});
You can attach event to element when you create it --
var ele =$("<a href='#'>Link</a>");
ele.on("click",function(){
alert("clicked");
});
$("#div_element").append(ele);
Just attach the click handler to the anchor BEFORE you append it.
$("#div_element").append($('test').click(function(){alert("test")}));
Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});
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().
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()