Javascript learned during the week

published Sep 27, 2012 09:11   by admin ( last modified Sep 27, 2012 09:11 )

I am doing a lot of javascript programming this week so here some things I have picked up.

 

Javascript debuggers in Firefox and Chrome

Chrome's built in seems the better one compared to Firebug on Firefox, but some things are hidden behind miniscule non-descript widgets in Chrome. i still cannot see how to select an element with the mouse on the page and get the source code to jump there though. Other way works fine.

 

jquery

When you select for an element in jquery, even if it is for an element with a specific and hopefully unique id, it will return an array, so you will have to extract the one you want. The slice method works well for that: result.slice(0) for first (and possibly only) element, and result.slice(-1) for last.

The clone() method is very nice.

 

If you miss python's "for .. in" syntax for iterating over things, there is an ".each()" method in jquery that accomplishes the same more or less.

 

javascript and prices

When handlig currencies with decimals, it seems to be ok to use parseFloat() to convert it into something numerical, but that can introduce rounding errors when doing arithmetic on the numbers. That seems to be handled by using var.toFixed(2) in the end. A bit of a patchwork.

Another way would be to multiply the prices by 100 and then use parseInt and just work with integers I suppose.

 

Submitting two forms at once

Can be done in at least two ways in javascript. You can submit one with XML-RPC or similar but the method I used was to have the first one submit to an invisible iframe with an appropriate target atribute in the form.  In that way you are still on the original page when the second form submits. Otherwise you would be somewhere else and the second submit would not work. I found this iframe technique in a discussion forum but I have closed that page alas.