Monday, December 15, 2008

Code generation with jQuery

Update: changed post title (content still same)

Sometimes, when you are developing in javascript, you need to reference many form inputs on a page, which can be time consuming (typing each one out). With jQuery, you can reduce the time by using jQuery to write the code (which you then copy and paste). For example (simplified, as you probably would not have fields named field1, field2, field3 etc):

var $field1 = $("[name='field1']");
var $field2 = $("[name='field2']");
var $field3 = $("[name='field3']");
var $field4 = $("[name='field4']");
var $field5 = $("[name='field5']");
var $field6 = $("[name='field6']");
var $field7 = $("[name='field7']");
var $field8 = $("[name='field8']");
var $field9 = $("[name='field9']");

This simple script can be used to create the aforementioned code. Includes an ASP.NET fix (if you don't want names like $ctl00$Content1$Field1)

$(
 function()
 {
  var $inputs = $(":input");
  var $textarea = $("<textarea>").css({width: "100%", height: "200px"});
  $inputs.each(
   function()
   {
    // $textarea.append("var $" + this.name + " = $(\"[name='" + this.name + "']\");\n");
    // ASPNET fix to get the name as set server side
    $textarea.append("var $" + ASPNETFix(this.name) + " = $(\"[name$='" + ASPNETFix(this.name) + "']\");\n");
   }
  );
  $("body").append($textarea);
 }
)

function ASPNETFix(name)
{
 return name.split("$").pop();
}

Simply save this into a separate JavaScript file (tweaking as needed), include on your page, then copy the text generated in the textarea at the bottom of the page.

This could also save time in other languages, as you control the output (could be C#, VB.NET, PHP, Python etc).

No comments: