Optimized jQuery code check I am new to jQuery, and after spending weeks to convert my pages using jQuery, I am now reading about jQuery optimization. In that effort, I'm rewriting one of my functions. Please comment whether it is right (both are working).

Previous

$("#mydiv").empty();
var i = 2;
$("#axisa option").each(function() {
    $("#mydiv").append("&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;");
    updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
    i++
});

$("#axisb option").each(function() {
    $("#mydiv").append("&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;");
    updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
    i++
});
$("#hiddendiv").show("slow");


Optimized

var mydiv = $("#mydiv");
var mywid = $("#wd").slider("value");
var myhet = $("#ht").slider("value");
var total = $("#axisa option").length + $("#axisb option").length+2;

mydiv.empty();
var design = "";

for(var i=2;i&lt;total;i++){
    design += "&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;";
}
mydiv.append(design);       
i = 2;

$("#axisa option").each(function() {
    updateCharts(mywid, myhet, $(this).val());
    i++
});

$("#axisb option").each(function() {
    updateCharts(mywid, myhet, $(this).val());
    i++
});
$("#hiddenDiv").show("slow");
Here are some general optimizations that I usually do.

When you have multiple var declarations you can separate with "," making it a bit easier to read and less of a hassle to write:

var mydiv = $("#mydiv").empty(),
    mywid = $("#wd").slider("value"),
    myhet = $("#ht").slider("value"),
    etc = etc.....


Also when I name my variables, ids, classes, etc. it's good to put names that reference what's inside the element, or the role it plays. It will help you remeber what does what when you get into big projects with lots of these declarations.

As a rule of thumb, if you have to call on an element more than once, you should cache its value. This way jQuery doesn't have to jump into the DOM and look for that element each time you call it. You should also try to limit the scope of elements jQuery has to look through to find the one you want. You can use the type of element previous to the id/class. For example:

$("#mydiv").doSomething();
$("#mydiv").doSomethingElse();


Instead do:

var mydiv = $("div #mydiv");

$(mydiv).doSomething();
$(mydiv).doSomethingElse();


Like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called 30 Days to Learn jQuery. He does a really good job of explain some basic principals as well as some more complex concepts.