Alessandro Lacava’s Blog

Google
 

March 31, 2008

How to disable all the elements of a form using JavaScript

Filed under: Computer, JavaScript — alessandrolacava @ 3:41 pm

Here's a little JavaScript function that disables all form elements:

JavaScript:
  1. function disableElements(formName)
  2. {
  3. var fm = document.forms[formName];
  4. for(var i = 0; i <fm.elements.length; ++i)
  5. {
  6. fm.elements[i].disabled = true;
  7. }
  8. }

As you may have noticed the only parameter you need to pass is the form name.


November 26, 2007

Capturing groups using regular expressions (RegEx) in JavaScript

Filed under: Computer, JavaScript — alessandrolacava @ 4:21 pm

There are whole books about regular expressions so this post shouldn't be intended as an exhaustive resource on the subject. It just shows how to extract a substring from a string using regular expressions in JavaScript so it must be considered just a tip not a tutorial on RegEx. Look at the following example:

JavaScript:
  1. var str = "http://www.alessandrolacava.com/?code=ALE69";
  2. var regex = /code=(\w+)&?/;
  3. var results = regex.exec(str);
  4. if(!results)
  5. {
  6. alert("no match");
  7. }
  8. else
  9. {
  10. // first group
  11. alert(results[1]);
  12. }

The previous code extracts the string that follows the code= part of str. That string is captured in the first group of the RegEx, that's why I use results[1] to display it. When you utilise groups--through the use of parenthesis ()--you can refer to them using indices, starting from 1. Indeed, at the index 0 you find the whole match. In the previous example, results[0] is equal to code=ALE69


Next Page »