Archive for the 'javascript' Category

javascript void(0) for HTML link

May 27, 2012

To create a HTML link which does nothing when user clicks it,  use  like below


<A HREF="javascript:void(0)">Click here to do nothing</A>

When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

References -

https://developer.mozilla.org/en/JavaScript/Guide/Expressions_and_Operators#void

Here is a stackoverflow.com link, which answers why  void(0)  is better than using #  for this requirement

http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0

Referencing variables in setTimeout function – Javascript Closures

May 26, 2012

Requirement

- Reference For loop variable i  in setTimeout function

Wrong way


for(var i = 1 ; i <= 10; i++) {
console.log('i in for :: ' + i);
setTimeout(function() {
console.log(' i in timeout :: ' + i);
}, 2000);
}

Ouput


i in for :: 1
i in for :: 2
i in for :: 3
i in for :: 4
i in for :: 5
i in for :: 6
i in for :: 7
i in for :: 8
i in for :: 9
i in for :: 10
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11

Right way using Closures


for(var i = 1 ; i <= 10; i++) {
console.log('i in for :: ' + i);
setTimeout(function(j) {
return function() {
console.log(' j in timeout :: ' + j);
}
}(i), 2000);
}

Ouput


i in for :: 1
i in for :: 2
i in for :: 3
i in for :: 4
i in for :: 5
i in for :: 6
i in for :: 7
i in for :: 8
i in for :: 9
i in for :: 10
j in timeout :: 1
j in timeout :: 2
j in timeout :: 3
j in timeout :: 4
j in timeout :: 5
j in timeout :: 6
j in timeout :: 7
j in timeout :: 8
j in timeout :: 9
j in timeout :: 10

References  -
http://jibbering.com/faq/notes/closures/

https://developer.mozilla.org/en/JavaScript/Guide/Closures

javascript undefined, null, undefined property, 0, false, ”, ==, ===, typeof

March 22, 2012

== Equals

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison.

=== Strict equal

Returns true if the operands are strictly equal  with no type conversion.

typeof

The typeof operator returns a string indicating the type of the unevaluated operand.

typeof undefined === ’undefined’

undefined

A variable that has not been assigned a value is of type undefined.

false

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (“”), or undefined.

null

null is an object. It’s type is null. Null and Undefined types are == (but not ===)

Undeclared variable

  1. /* var z*/
  2. z.x  // throws a ReferenceError

Check for undefined variable

  1. var x;
  2. if (x === undefined) {
  3.    // these statements execute
  4. }
  5. else {
  6.    // these statements do not execute
  7. }

check for undeclared variable

  1. // x has not been defined before
  2. if (typeof x === ’undefined’) { // evaluates to true without errors
  3.    // these statements execute
  4. }
  5. if(x === undefined){ // throws a ReferenceError
  6. }

check for object property

  1. var myobj = {‘a’:'a’};
  2. myobj.hasOwnProperty(‘a’) // true
  3. var myobj2 = Object.create(myobj);
  4. myobj2.hasOwnProperty(‘a’) //false
  5. ‘a’ in myobj2 // true

check for null

  1. var c = null
  2. if (c === null) { // true
  3. }

References

http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators

https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

XMLHTTP AJAX abort(), jQuery abort()

March 10, 2011

I was looking if there was a way to stop an already running AJAX request, like we can stop an http request using browser stop button. Yes there is a way to stop it using abort() method of the XMLHttpRequest object . More details about this here http://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_a_1.html

Javascript javadoc – JSDoc

March 4, 2011

I was looking if there was any standards for writing Javascript API documentation and if there is a tool to parse and generate the document.

I found one which does this http://jsdoc.sourceforge.net/, seems like it solves the purpose I am looking for, have to try it out.

jQuery Form serialize method – does not post disabled fields

February 24, 2011

http://api.jquery.com/serialize/

Today I had a problem where I had some disabled fields which were not getting serialized, I got two solutions for this

Validate/Revalidate a single field using jQuery validator

February 23, 2011

If you have a requirement to just do a single field validation, instead of calling the form validate method which will validate all the fields, then you have to use valid() method on the element

For example if your form has field

<input type="field" name="username" id="username"/>

to validate only username field, use code

jQuery('#username').valid()

But of course you have to link the jQuery validator plugin with your form before you call this method

Related Stack overflow post link here – http://stackoverflow.com/questions/1378472/jquery-validate-can-i-re-validate-a-group-of-fields-after-changing-one

jQuery JSONP (JSON with padding) – success method not called

February 23, 2011

Possible reasons for JSONP success method not getting called

  • In jQuery.getJSON method check if you are adding the
    callback=? param to your URL
  • Check if your server code serving JSONP request is returning proper JSONP response,

    For example sample server JSONP java code and response taken from IBM Developerworks article given below,
    Java code

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    String jsonData = getDataAsJson(req.getParameter("symbol"));
    String output = req.getParameter("callback") + "(" + jsonData + ");";

    resp.setContentType("text/javascript");

    PrintWriter out = resp.getWriter();
    out.println(output);
    }

    JSONP Response Format

    jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});

To get a good understanding of JSONP you can read this IBM Developerworks article http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

jQuery Validator – Error: $.validator.methods[method] is undefined

February 22, 2011

Error: $.validator.methods[method] is undefined

I was getting this error when using jQuery validator, found the reason for this error was because I didn’t define the custom validator methods which I had assigned in the validation rules. More about jQuery custom validation method here – http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

what http error code to use for validation error

February 18, 2011

I was using 500 – Internal Server Error for validation errors, but problem was the application error handler caught this and shows generic error page, which causes validation logic to fail. So instead we can use

Either use code 400 – Bad Request
or code 200 – with the error message

http://stackoverflow.com/questions/362618/proper-use-of-http-status-codes-in-a-validation-server

Follow

Get every new post delivered to your Inbox.