How to use jQuery's trim() function - javascript

As discussed in many questions on stack - IE 8 wont accept .trim(), but the jQuery framework takes care of that.
I don't know how to translate my function to use that version of trim (I thought I was already using jQuery), could someone advise? Here is my code:
$('input').val(function(index, val){
return val.replace('Please Select', '').trim();
});
This is designed to replace the string with nothing.
I've tried:
$('input').val(function(index, val){
return val.replace('Please Select', '')$.trim();
});
but that was no good.

$.trim(val.replace('Please Select', ''))
http://api.jquery.com/jQuery.trim/

IE8 doesn't have a native trim method, generally, I just augment the prototype:
if (!String.prototype.trim)
{
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,'');
};
}
This is the shortest regex to trim a string, but I have heard it say that .replace(/^\s\s*/,'').replace(/\s*\s$/,'') is (marginally) faster... the choice is yours
If you really want to use jQuery for this, of course, you'll have to make the target string the context of the called method ($.trim calls the method on $ === the jQuery object), so make the String a jQ object:
$(' foo bar ').trim();//returns "foo bar"
//compared to augmented prototype:
' foo bar '.trim();//returns "foo bar"
The benefit of an augmented prototype is that you don't have the additional overhead of creating a new jQuery object, whereas using the prototype-approach relies on JS to wrap the string in a native String object and apply the method to that. Basically, it's the same operation, but it should be a marginally more efficient, because jQuery does a bunch of checks to any string passed to the jQuery constructor ($())

Try this:
$.trim(val.replace('Please Select', ''));
Here's the Trim() entry in the documentation.

Related

difference between $ and $$

I used $ instead of document.getElementById() in javascript and i don't know what is the use of $$. Can any one please tell me what is the use of $$?
Here is the code:
var link_object = $$('a[class="menu_item"]');
if (window.location.href.search('inident.do') >= 0) {
link_object.each(function (elem) {
if (elem.innerHTML == 'Create an Incident') {
elem.style.fontWeight = 'bold';
elem.style.color = 'black';
}
});
}
The single $ is usually a short name for jQuery object.
The double $$ could be anything.
In Angular, seems to designate a private identifier.
You can do something like this when you hate your colleagues :
$$$$($$$[$]);
$ is the selector in jquery. $$ doesn't have any specific meaning in jquery
so you can use it in your own way.
like this
function $$(){
alert('hello');
}
$$();
There may be other libraries like jquery which use $ or may be use $$.
since $ is valid symbol in javascript for variable and function names
it is the best way to simplify the dom selection instead of using long
document.getElementById() like functions.
contribution of Mr. Robg
In jQuery, $ is a function that takes different types arguments. It will accept functions, arrays, objects (native and host), strings or nothing at all. If it gets a string, it will work with a selector or HTML
$$ doesn't have any particular meaning for jQuery. But if you are using some library who can conflict with jQuery, you can change the name of $ function to anything you want by using jQuery noConflict function;
You should look for something like this early in your code
var $$ = jQuery.noConflict();
Are you sure this is jQuery ? It looks like mootools.
In mootools, $$() is the element selector function. It works similar to $() in jQuery.
$('id')
returns the element with id 'id'.
$$('selector')
returns a collection of the elements corresponding to the selector passed.

call jQuery lib function identified with variable

I build recurring html with jQuery functions.
I'd like to give my functions more flexibility with $.append(), $.before(), and $.after(), etc.
Currently, I do something like
$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
if(domInsertMethod == 'append'){
$(domInsertID).append(htmlToInsert);
}
else if(domInsertMethod == 'before'){
$(domInsertID).before( ...
}
but I'd prefer (pseudo)
$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
$(domInsertID).window[domInsertMethod](htmlToInsert);
}
but that doesn't work for me.
Is this possible? If so, how?
Just use
$(domInsertID)[domInsertMethod](htmlToInsert);
DEMO: http://jsfiddle.net/UZKLY/
This works because the result of $(domInsertID) (or any $()) is a jQuery object, so it has properties and methods you want to call. Normally, you use dot notation to access them, but bracket notation is just as valid to use. Bracket notation is the only way to dynamically get a property/method (and allows for invalid identifier characters).
But be careful, because technically any method name could be provided, and therefore called. So it's up to you if you want to allow it or not.
As it stands, it doesn't make sense to add to $.fn, because you're not actually using the selected elements from the selector. It makes more sense to me to use this setup:
$.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
$(domInsertID)[domInsertMethod](htmlToInsert);
};
And you would call it like:
$.appendRecurringHTML("after", "#id", "html");
But if you wanted to use the selected element(s) as the target(s), you could use:
$.fn.appendRecurringHTML = function(domInsertMethod, htmlToInsert) {
return this.each(function () {
$(this)[domInsertMethod](htmlToInsert);
});
};
And call it like:
$("selector").appendRecurringHTML("after", "html");
DEMO: http://jsfiddle.net/UZKLY/1/
It preserves chaining, and will be applied to all matched elements.
Try this:
$(domInsertID)[domInsertMethod](htmlToInsert);
This approach creates jQuery object with your domInsertID first. Than selects domInsertMethod from that object's prototype chain and executes the method using htmlToInsert.

Operating on a string rather than a selector from a jQuery Plugin

I want to create a plugin that works like so:
var fmatted = $('someString').myFunction();
I've developed jQuery functions in the following manner:
$(someSelector).someFunction();
I know that the selector gets converted to a jQuery object and can be used via this in the plugin. However, if I want to use a string rather than a selector, I'm not sure how I can access that string within my plugin.
Basically, I want to be able to use a plugin to operate on something other than a selector, very much like jQuery's .trim() function, but I can't figure out how to access that within the plugin.
jQuery(selector)[docs] (or $(selector)) is used to create a jQuery object containing elements that match the selector. Although it is possible for you to create a method which ignores the elements and retrieve the original selector, this is not efficient and makes it more difficult to understand what your code is doing.
jQuery.trim()[docs] is not implemented like that. In fact, notice that jQuery.trim() isn't a method on a jQuery object at all! If it were, you'd invoke it like this:
jQuery(" foo ").trim();
Instead, you do this:
jQuery.trim(" fooo ");
.trim() is a method, but not a method of jQuery objects. It's a method of the jQuery constructor function itself (in some languages you would call this a "class method").
You're not creating an object and the argument is never treated as a selector. To add a function like this yourself, all you need to do is this:
jQuery.someFunction = function(message) { alert(message); };
More idiomatically, the default behaviour of the jQuery.extend[docs] will do this for you:
jQuery.extend({someFunction: function(s) { alert(s); } })
That's all you need!
use the selector property:
var jQueryObject = $('my string');
var originalString = jQueryObject.selector;// it'll give you 'my string'
Is this what you're after?
$.fn.makeLower = function() { return this.selector.toLowerCase(); }
$("FOO").makeLower(); // produces "foo"

Is it possible to access the DOM element 'this' in a non-function parameter argument in a jQuery plugin?

I have a potentially strange question about this and jQuery plugins
As I understand it, the following is a very basic jQuery plugin:
$.fn.clickclone = function(param){
return this.click(function(){
param.apply(this);
});
};
(pretending that's a plugin that somehow extends click().)
So, if I pass a function as an argument, it does what it needs to do and properly accesses this as a DOM node. Easy.
That's all clear to me.
What's not clear is, is there any way I could pass a non-function argument to the plugin and have it properly access this from the arguments? ie, could I configure the plugin to do something like this:
$("#foo").pluginname(["foo", $(this).text() ]);
Such that for:
Bar
It would properly pass an array to the plugin, with the second item in the array returning the value Bar?
I'm doing this, basically, to provide syntactic sugar for my plugin, where you can pass an array as a shortcut (in addition to using a normal callback function as the main functionality). Except, doing that, I lose access to use of this. Hence my dilemma.
EDIT: This is evil, but, it seems like one work around is to pass the argument as a string and then eval it. Not a workable solution for me, but, it illustrates what I'd like to be able to do:
$.fn.clickclone = function(param){
return this.click(function(){
if(typeof param === "function"){
param.apply(this);
}
else if(typeof param[1] === "string"){
console.dir("This is evil: " + eval(param[1]));
}
});
};
There's no general way to do this without a function, since, in the purely mathematical sense, you are asking for a function of the input (that is, a function of this): something that depends on this in a certain way.
You could perhaps hack it with strings, like so, but you lose the flexibility of functions:
$.fn.alertMe = function (methodToAlert) {
alert(this[methodToAlert]());
};
// usage:
$("#foo").alertMe("text");
$("#foo").alertMe("width");
And if you find using a function acceptable but the this syntax confusing, you can simply do the following:
$.fn.alertMe = function (alertGetter) {
alert(alertGetter($(this));
};
// usage:
$("#foo").alertMe(function (x$) { return x$.text(); });
$("#foo").alertMe(function (x$) { return x$.width(); });
And for completeness I guess I should mention you could probably get away with an eval-based solution, looking something like $("#foo").alertMe("$(this).text()"), but eval is evil and I will neither write up nor condone such a solution. EDIT: oh, I see you have done so in an edit to your original post. Good job corrupting future generations ;)

Any difference between a $ wrap function and getElementById?

I mean a wrap function like this:
function $(id) { return document.getElementById(id); }
but in some code like this:
oDiv1 = $("postInfoDiv");
oDiv2 = document.getElementById("postInfoDiv");
alert(oDiv1 == oDiv2); // return false
alert(oDiv1.style); // error
alert(oDiv2.style); // correct
alert(document.getElementById("postInfoDiv").style); // correct
I got strange results as the comments imply.
I thought the first alert should return the true since they are the same dom object.
I thought the second alert should alert something like "object" or "CSS StyleDeclaration" but not "defined".
So what are the problems? Have you ever met this kind of problems?
thanks.
Your $ function is probably being overridden, potentially by a framework.
You should try doing alert( oDiv1.nodeType ) to see if it's a DOM element. alert( oDiv1.length ) to see if it's an empty array because you may be using jQuery on the same page which overrides your $ function.
oDiv1 may be an array-like object containing that item if jQuery is included. oDiv2 is an actual DOM reference. You probably need to compare oDiv1[0] to oDiv1, in which you reference the first element in the array which points to the actual dom element to make a fair comparison.
function $(id){return document.getElementById(id)}
$('content') == document.getElementById('content')
true
The custom $ function will work perfectly but if you're using a framework function it will return that array-like object instead of the DOM element.
You can also rename your function to something like function getID which would be unique and not conflict with framework $s.
My main concern with this is that it will confuse the heck out of someone the first time they read your code, especially if they are used to coding with a JavaScript framework such as jQuery.
For this reason alone I recommend you do not use this particular syntax for your wrap function.
BTW note that even when jQuery is not loaded, Firebug provides its own $ function, which may participate to confusion.

Categories

Resources