Hard-won Javascript/JQuery wisdom and useful (benign) hacks
Last updated:- invisible elements (display:none)
- setTimeout for debugging
- selectors for DOM elements
- html button default type is submit!
- .get does not return a jQuery object. Use eq instead
- hasOwnProperty()
- scoped jQuery queries
- reading pure text from the server
invisible elements (display:none)
invisible (display:none
) elements cause all sorts of trouble: sometimes (always?) you can't interact with an element if it's invisible.
setTimeout for debugging
if you have a piece of code that doesn't work no matter what, try wrapping your code in a setTimeout()
call and test if it still doesn't work.
A few microseconds can make a lot of difference to javascript but not much difference to human eyes.
selectors for DOM elements
To get the selected text of a dropDownBox:
$("#aDropDownList").change(function(){
console.log($(this).children("option").filter(":selected").text());
});
jQuery get selected text from dropdownlist at stackoverflow
html button default type is submit!
Not strictly javascript or jquery but, since we deal with forms all the time, it's good to know that if you don't define a <button>
type, it will default to submit and cause any forms to submit!
This has caused me some hard-to-debug problems, even though I already knew about it, so I figure it's worth mentioning.
.get does not return a jQuery object. Use eq instead
If, for instance, you have a selector that returns many elements, you probably want to use jquery's eq(index)
to fetch one of the elements.
If you just use get(index) you'll still get the element but it won't be a jquery object so you won't be able to do anything with it.
So, assuming you have a document with two <div>
s:
var elements = $("div"); //will yield a list of the two divs
elements.eq(1).html("foo"); //works and sets the content of the second div
elements.get(1).html("foo"); // does not work and an error is thrown
hasOwnProperty()
use obj1.hasOwnProperty('attribute1')
to find out whether obj1
has an attribute named attr1
scoped jQuery queries
To search for an element inside this element only:
$('input[type="checkbox"]',this);
This allows you to perform queries but give as container another element.
reading pure text from the server
Any text sent directly from the server (for example, via PHP echo
function) maybe or may not reach the browser exactly as it was sent.
Therefore, if you are writing, for instance, a $.post
jQuery ajax request, make sure your check first whether the data has arrived exactly like it was sent (i.e. no \n before or after the actual text or anything like that).
I recommend you check pure text send from the browser using the String.match
javascript function, for example:
$.post(
location.href,
{
param: 'some_value'
}
,function(data){
if(data.match(/success/)){
//success
}else if(data.match(/failure/)){
//failure
}else{
//neither one nor the other, do something like send an alert()
}
});