JQuery Loop over JQueryObjects - javascript

I have a method, which will accept a parameter of a JQuery Object and will calculate totals for a section. So if you give it a JQuery Object of a div containing the section it will calculate a total for it
so you can do this:
var $totalcompletion = CalculateSectionCompletion(jQuery("#Section1"));
Now I have multiple divs with the class of section container. I want to be able to call the above method on any div with that class.
I'm doing this:
jQuery("div.SectionContainer").each(
function(i, valueOfElement){
CalculateSectionCompletion(valueOfElement);
});
The problem is the valueOfElement is actually the DOM object and not the JQuery Object, so I can't pass this in to my method.
Is there anyway I can loop through all JQuery Objects selected by a query, without writing some dirty code to extract the Id from the DOM object, and call JQuery(valueOfElement.id) and pass it in?

You can wrap any DOM element in $(..), as you do with $(document).
So I think you should be able to
jQuery("div.SectionContainer").each( function(i, valueOfElement){
CalculateSectionCompletion($(valueOfElement));
});

You could also ignore the i and valueOfElement arguments altogether and use this.
jQuery("div.SectionContainer").each(function(){
CalculateSectionCompletion(jQuery(this));
});
You could even make the CalculateSectionCompletion function wrap it's argument in the jQuery object.
jQuery("div.SectionContainer").each(function(){
CalculateSectionCompletion(this);
});
function CalculateSectionCopletion(e){
jQuery(e).dostuff();
}

Related

findpos work on ID but not class in javascript

highlightedBlock = document.getElementById("post-" + getLinkID);
console.log(findPos(highlightedBlock));
console.log(findPos($('.bar-holder')));
my second console.log return NAN, and I tried many different classes. Is this normal?
Looks like it is looking for a dom element reference(from the parameter sent to first call)
The jQuery method returns a jQuery wrapper object, not a dom element reference that could be the reason for the said result.
console.log(findPos(highlightedBlock));
console.log(findPos($('.bar-holder')[0]));
If you have multiple elements with the said class, then you will have to iterate through each element and then call findPos for each of them
$('.bar-holder').each(function () {
console.log(findPos(this))
})

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

How i can do this in jQuery? any trick to pass selector instead of jQuery object in $

In JavaScript if I append a child which has an ID to another place then it's removed from original location where they currently are.
In javascript I have an event where I can get selector by using this inside the function
$('.').event(function(){
this
});
This is passed to another function and they work fine. Now I want to pass the clone instead of the object; and remember that this does not have ID.
The old code works by passing this to function as DoSomething(this)
if I make a clone using jQuery clone then I have the jQuery object. So how do I get a reference to this instead of the jQuery object when working with the clone?
var clone = $(this).clone() // this is jQuery object.
//how do I get this out of clone?
if I append a child which has an ID to another place then it's removed from original location where they currently are.
Yes, but the same is true of a child node that doesn't have an id attribute as well. An id is only an easy way for you to get a reference to the Element node object; it makes no difference to DOM insertion of cloning behaviour.
In javascript I have an event where I can get selector by using this inside the function
No, this in an event handler gives you the DOM Element node object, not a selector string. A Node can be turned into a jQuery wrapper around it using $(node) and a selector can be turned into a jQuery wrapper on the list of matching nodes using $(selector) but other than this overloading in the jQuery API they're completely different animals.
To pull a Node back out of a jQuery wrapper you can use the get() method or simple array-like access:
var clonedNode= $(this).clone()[0];
var clonedNode= $(this).clone().get(0);
to taste. (get() has some extra features which you don't need here.)
To get the selector used to create a jQuery wrapper you can use the selector property, but this won't return anything if the wrapper was created from a node object ($(this)) rather than a selector.
$(this).clone().get(0). This will get the first matching DOMElement from the jQUery object.
To get the DOMElement object from a jQuery object use get(0):
var clone = $(this).clone(); // this is jQuery object.
var el = clone.get(0); // this is DOMElement object

Using Jquery, call function on selection just once

Say i have a selection of textboxes like this;
var arrayoftextboxes = $('.textbox1, .textbox2, .textbox3');
Is there a way I can call a function on each one in a simpler way than this?
It only needs to be called once.
arrayoftextboxes.each(function(i){foo(arrayoftextboxes[i]);});
I tried
arrayoftextboxes.load(function(){foo(this)});
and
arrayoftextboxes.bind(function(){foo(this)});
but the functions dont seem to be called.
You can do this:
$('.textbox1, .textbox2, .textbox3').each(function() { foo(this); });
The .each() call creates a closure, inside it this refers to the DOM element you're currently on, but it may be better to write what you have as a jQuery plugin. Or, if you just use this inside foo (instead of the DOM element as a parameter) you can shorten it down to:
$('.textbox1, .textbox2, .textbox3').each(foo);
Here's a demonstration of that method
Also, make sure you're running this on document.ready like this:
$(function() {
$('.textbox1, .textbox2, .textbox3').each(foo);
});
Otherwise the DOM elements may not be there to find, making that selector return an empty array (so nothing to run on).

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources