jquery attributes from multiple elements - php

I am trying ot figure how to use jQuery to get the value of html attribute of many elements. My webpage updates dynamically using ajax. I have an attribute called number for in element in the part that is updated. I want to use the attribute value from each element so that i can use that data as parameters to a php file link. I have come across jquery's .attr() function, but it only seems to take the attribute value of the first element if finds. But what I want to do is get the attribute value for each element so that when I click on that element its corresponding attribute value is sent as parameters to the php file.
Thanks

you can combine attr() with .each() method.
e.g.
$("div").each(function(){
$(this).attr("number");
});

Disclaimer: This most likely does not respond to the OP question (after re-reading), but will stay for some time in case it fill some need of the OP.
Use the .map() method
var numbers = $('[number]').map(function(){
return $(this).attr('number');
});
this will create an array filled with the number attribute of all the elements that have one.

Inside a click handler (or any event handler), this will refer to that element, for example:
$("#content").delegate("a", "click", function() {
alert($(this).attr("something")); //alerts "something" for the <a> you clicked
});
In this case we're using .delegate() because you said "My webpage updates dynamically using ajax", so just attach the handler to a parent element that's not replaced via AJAX and it'll work for all elements you add beneath...in the example above we're binding to all <a> elements, but just change the selector accordingly.

Related

Keeping only certain elements inside html with Jquery

I'm trying to keep only certain elements that has been added to a text area using jQuery. I'm using MutationObserver to find any new items added to a div and copy that to the form.
// passes content to the string, new items are also found
// and added using the MutationObserver
//
var stringContent = $("#OriginalOutput").html()
But, in this case I'm looking to get all the new 'li' found in the html.
I tried some methods like this for example:
var stringContent = $("#OriginalOutput").clone().find('.container')
.insertAfter().end().html();
this works but only give me the first 'li' element inside. I also tried other ways replacing insertAfter with something else that left me with the same result, but not giving all the 'li' elements it finds.
I already have the ul element being called somewhere else, and i just need to pass all the 'li' elements found into the string. This way I can use it on here:
//edited from #OriginalOutput to #output
$("#output").val("<ul class=\"mylist\">\n" + stringContent + "</ul>");
Another method i tried was removing the elements i didn't needed just to keep all the 'li' that's been added, but the problem I was having was i didn't know how to remove each class and if i remove the parent div that's holding all the elements, it would just take everything inside it including the 'li' elements, so I'm sure I can't do that. Although I did try to get it out using PHP with str_replace on the final output, but was able to get only certain elements out since most of the elements i need to remove outputs unique ids.
Use the .each() function. If you're only getting one element delivered, this may help. Change your jQuery to look like this:
var stringContent = '';
$("#OriginalOutput").clone().find('li').each(function(){
var t = $(this);
stringContent += t[0].outerHTML;
}
UPDATE
Per asker's comments:
My guess is then that your problem isn't to do with pulling the items, but rather with putting them in. I'd change the way you're inserting them to this:
$("#OriginalOutput").clone().find('li').each(function(){
var t = $(this);
$("#OriginalOutput").append(t);
});
I'm not sure why you'd chosen val() in the original answer, I just assumed that $('#OriginalOutput') was a hidden element. If it is a hidden element, you might want to construct a clone from scratch in your function, like this:
var myCloneElement = $(document.createElement('ul'));
myCloneElement = $('#myTargetList').clone();
$("#OriginalOutput").clone().find('li').each(function(){
var t = $(this);
myCloneElement.append(t);
});
$('#myTargetList').html(myCloneElement.html());
Give this a try:
var stringContent = $("#OriginalOutput .container").clone().find(':not(li)')
.remove().end().html();

how do i make a select box populate div on change

so, I have read just about every question on this subject, but the solutions don't work for my project, it seems that when I change the dropdown, it does the first event, but when I change to a different element it doesn't do anything else, but when I do this with an alert message it changes every time.
here is what I have to demonstrate what I mean
I tried .post it works great until I add php and all the dynamic functions, is it because I used $('#updateDiv').html(url);
I also hide and showed the div based on the change of the dropdown, but all that did was hid and show the div, I want the div to show the content based on a list of categories.
the PHP side will be dynamic, but if I do .html() none of the php renders properly.
http://fiddle.jshell.net/LrxUS/
$.post(url, function(data) {
$("#updateDiv").html(data);
});
As per the fiddle, you have specified
var mydropdown = $('#mydropdown');
but in the change function, you have specified $(mydropdown), either define only id in the variable or the object. Like,
var mydropdown = '#mydropdown';
$(mydropdown).change(function() {}
After that use $.ajax to get the dynamic content.
Ok, lets make it the simplest so that there is no room for mistake in the client side script. Use $.load method defined here.
AS:
$("#updateDiv").load(url);
And don't forget to check what your firebug, chrome inspector or fiddler says about your request in case if you don't get the required result.

JQUERY AJAX for each loop custom attributes

This question is related to another one I asked yesterday and its link is:
Parse HTML in jquery through ajax into elements and replace each corresponding on page
Basically i want to call a php page with ajax and replace the elements in the response with the corresponding ones on the page. I got the following function in an answer:
$(data ).filter('.maindiv').each(function (index)
/* "this" is the current div in response*/
$('#'+this.id).replaceWith(this);
});
The above function woeks well when the div I want to replace has a regular id= but if use a custom attribute like gid= for example it won't work. How can i fix this??
Thanks
Use attr for custom attribute instead of using this.id you can use $(this).attr("YourAttr");
$(data ).filter('.maindiv').each(function (index)
/* "this" is the current div in response*/
$('#'+$(this).attr('gid')).replaceWith(this);
});
You can select node with a gid attribute with:
$('[gid]').replaceWith(this);
you can even be more precise by selecting only the node which has the gid value you want
$('[gid="hello"]').replaceWith(this);
Hope it helps
For data you can use a custom attribute. HTML5 specificies the use of a data- attribute. The cool thing is that this works in HTML4 too! jQuery can read it by using the data method.
I'll recommend:
<div class="maindiv" data-grid="myGrid">...</div>
$(data).filter('.maindiv').each(function (index)
$('#'+$(this).data('gid')).replaceWith(this);
});

How to show/hide one dynamic element (div) at a time with jQuery

This is my first attempt at jQuery and I'm using a basic tutorial I found here: http://papermashup.com/simple-jquery-showhide-div/#
This is my current code and how the jQuery works: http://jsfiddle.net/mZQsu/
As you can see, when you click the '+/-' it opens all 4 of the tables/DIVs.
How can I modify this code to open just the relevant secondary table/div according to the original table?
(Please note the secondary tables are generated dynamically from PHP and SQL data)
Thanks.
P.S all my code is here http://jsfiddle.net/mZQsu/ instead of clogging up this question page :)
DEMO fiddle
$('.toggler').click(function() { // had to differentiate the main togglers with a new class
var ind = $(this).parents('tr').index()-1; // could change
$(".slidingDiv").eq(ind).slideToggle();
});
$('.show_hide').click(function() { // this are the 'togglers' inside the big menus
$(this).parents(".slidingDiv").slideToggle();
});
The best solution would be if you tag each of your div's with an id. E.g.
<div class="slidingDiv" id="ip_127_0_0_1">
and then modify the equivalent links to do
$("#ip_127_0_0_1").slideToggle();
so just the associated div gets expanded.
See my updated fiddle: http://jsfiddle.net/mZQsu/1/
You can use the index of the row, and toggle only the matching row of the other table using jQuery index and eq
See the relivant docs here:
jQuery index
jQuery eq
This should work:
$('.show_hide').click(function() {
$(this).parents(".slidingDiv").slideToggle();
});
Since the slidingDiv class is a direct parent of the show_hide link, I could have used "parent" rather than "parents". The latter provides more flexibility because it traverses all ancestors looking for the class.
Here is a modified code - http://jsfiddle.net/mZQsu/3/
I have added show-hide1, show-hide2, show-hide3, show-hide4.
And clicking on it opens respectively slidingDiv1, slidingDiv2, slidingDiv3, slidingDiv4.
When you are binding to an event: You can always grab that event target and reference it.
$('.show_hide').click(function(e) {
$(e.target).parent("div.slidingDiv").slideToggle();
});
.parent() is a good place to start, but .closest() also might work. That being said, this is the preferred way to go about it.
On a side note if you ever want to do the opposite you could use .not(e.target) and all the other elements except for the one your click will be called.
Since your html is PHP-generated, it should not be a problem to include unique IDs for both +- links and sliding divs, for example:
a href="#" class="show_hide" id="show_hide2"
And
div class="slidingDiv" id="slidingDiv2"
Then in your click function you get the index of the div that you want to open:
$(.show_hide).click(function(){
var $str = $(this).attr('id');
var $index = $str.charAt( $str.length-1 );
});
Now you can use index to open the div:
var divName = "#slidingDiv" + $index;
$(divName).slideToggle();

Cannot control content added dynamically with .load

I have content that I'm loading using an AJAX call and displaying the HTML (consisting of divs, etc) inside of a ul parent.
Now I've written a series of .click and .hover functions that work perfectly on everything, right up to where my content is dynamically loaded, and then don't work at all on the dynamically-loaded content.
I've gone through all my div ids to make sure they are correct and they are. Is there a way to gain control over the AJAX-loaded material?
The problem is that your code run only with the elements that existed at that time and no the "future" elements. You have 2 choices:
1) Re-run your "onload" javascript code (that was applied on document ready) after you load your ajax content.
2) Use .live() instead of .bind():
So change
$('#selector').bind('click', function(){..
To
$('#selector').live('click',function(){..
The difference is that live uses the elements that match the selector now and in the future, versus bind uses the elements that match the selector only at the time it's called.
Hope this helps. Cheers
Your event handlers are bound to elements that exist at the time that they are set.
Either re-attach the handlers to the new, dynamically-created material, or make use of live or delegate; these "attach a handler to the event for all elements which match the current selector, now and in the future".
You should either rebind the events after the content is loaded or use
.delegate (api) to have the event attached automatically to newly loaded elements.
something like:
$("ul#container").delegate("li", "hover", function(){
doStuff();
});
$("ul#container").delegate("li", "click", function(){
doOtherStuff();
});
Change
$('a#whatever').click(function(){....
To
$('a#whatever').live('click',function(){....

Categories