What is 'this' as a parameter in a JavaScript function - javascript

I have a SELECT html element which has the onchange event like this:
onchange="myFunction(this)"
What kind of object is this in this context?
function myFunction(control){
var jqObject = $(control);
...
..
var jqObject2 = jqObject.find('select.mySecondSelect')
}
Inside my function I get another object with jQuery (jqObject2) which represents another select HTML Element and I want to cascade this object to a similar function like myFunction(this)
So, how can I transform the jQuery object as JavaScript object but like this as a parameter does?
I found in some posts that calling the jqObject.get(0) or jqObject[0] is what I should need, however I don't think it is the same thing. Because with get(0) I am getting the native DOM element but not specifically as an object AFAIK.
Update
This will be the whole scenario:
HTML
<select name="lstCountry" class="country" onchange="onCountryChange(this)">
<option value="USA">USA</option>
<option value="MEXICO">Mexico</option>
</select>
<select name="lstState" class="state" onchange="onStateChange(this)">
....
</select>
JS
function onCountryChange(control){
var oCountry = $(control);
var oState = oCountry.closest('tr').find('select.state'); //<== oState is never empty or unspecified. I always get the object correctly.
//do operations related to the country
//specific case, call the onStateChange
onStateChange(oState.get(0)); //<== Here!!
}
function onStateChange(control){
var oState = $(control); //<== When I call this from the function onCountryChange, control is equals to unspecified. BUT not when the user really perform the onchange on the control state (select Element) manually
//do operations related to the state
}

this in an onXXX attribute is the DOM element itself. So in this case it's the <select> element that the user changed. $(control) creates a jQuery object that contains the DOM element. Given a jQuery object that contains a collection of elements, you can use jqObject.get(n) or jqObject[n] to get the nth element in the collection. So if there's just one element in the jQuery object, jqObject[0] will return that element.

What you found in those post is the correct thing.
The this in your code (onchange="myFunction(this)") refers to the raw html element (that the attribute is applied).
So using jqObject2[0] will point to the raw html element of the followup query.

In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
Via- http://www.quirksmode.org/js/this.html
And as #Barmar mentioned, jqObject.get(0) or jqObject[0] basically returns the first object from an array, jqObject.get(1) or jqObject[1] returns the second and so on.

Related

information about this type of selection in jquery $('.myclass',obj).length;

anyone know where can I get information about this Type of selection in jquery
I found it in a .js file and I want to know about it.
I focus on Jquery api doc but in vain I dont find it.
var obj=$('#id1');
var t = $('.slidenews',obj).length;
exactly that what I want to know about.
var t = $('.slidenews',obj).length;
$('...', element) looks for ... in element instead of the whole document. So in this case, it will look for all elements with class slidenews in the #id1 element.
.length returns the number of such elements found
Therefore, if obj contains the element with ID id1, then $('.slidenews',obj).length returns the number of elements with class slidenews that are contained inside the element with ID id1.
Relevant documentation:
jQuery(selector, [context])
selector
Type: Selector
A string containing a selector expression
context
Type: Element or jQuery
A DOM Element, Document, or jQuery to use as context
length
Description: The number of elements in the jQuery object
$('.slidenews',obj) is basically context selector. It will be converted into obj.find('.slidenews') and .length returns the no of such elements
Reference
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.
It same like:
obj.find('.slidenews')
In your case: obj - must be DOM object. if obj is falsy it will be replaced to document

JQuery select by ID vs document.GetElementByID

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);

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

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.

JQuery Loop over JQueryObjects

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

Categories

Resources