Category: JavaScript

Easier Javascript Form Validation

I was racking my brain trying to find the best way to do form validation across a huge application, and I knew what I wanted to do. I wanted to implement a single function I could use to validate every form, without needing to resort to all kinds of manual coding.

I decided to use the class attribute for a little more than formatting. It's an ideal space to use for ad-hoc properties, since it allows as many class names as you want to put into a single tag.

Here's a basic form:

HTML:
  1. <form name='myForm' id='myForm' method='post' onsubmit='validate(this);'>
  2.   Name: <input type='text' class='required' name='name' />
  3.   Address: <input type='text' class='min20' name='address' />
  4. </form>

Notice the class names above. I've used 'required' as the class for the first input, and 'min20' for the second. I want required to mean the field cannot be blank, and I want min20 to mean the field must contain at least 20 characters in order to be valid.

Here is the validate function, which takes a form object as a parameter:

JavaScript:
  1. function validate(frm) {
  2.   var elms = frm.elements;
  3.   var numElms = elms.length;
  4.  
  5.   for (var i = 0; i <numElms; ++i) {
  6.     if ( (/required/).test(elms[i].className) && !elms[i].value) {
  7.       elms[i].focus();
  8.       alert('You need to fill in this field to continue...');
  9.       return false;
  10.     }
  11.  
  12.     if ( (/min20/).test(elms[i].className) && elms[i].value.length <20) {
  13.       elms[i].focus();
  14.       alert('This field requires at least 20 characters in order to continue.');
  15.       return false;
  16.     }
  17. }

Now, those error messages suck. You'll want to do better, possibly using the name of the element, or the title attribute, or something else that will help it be more descriptive. That's outside the scope of this post, I'm just showing the mechanism for validation, bells and whistles on it are up to you.

~A!

Q&A Selecting in a Listbox after submit

This question was submitted on February 4th, 2008:

Hi,
I have a combo box called "A" which contains fruits and vegetables
and a list box called Types(i.e) which will display the corresponding types(Eg if we select Fruits then it will display apple, mango and if we select vegetable then it will display carrot, onion etc.
Based upon the selection in the list box and on clicking submit button it will populate the table which will containe prices.
On First loading the page both the combo box and list box will contain "select" as first option. Then we choose Fruits and their corresponding types listed in the List box and based on the selection in the list box and after clicking submit button the table gets populated. All the values are updated in the database.
On Reloading the page we should get the same value which we have selected in Combo Box "A" and list box "Types" and table also should be populated. I am getting the List box value from the database and i am iterating with the list of values in List box.
Eg If i selected Mango and then clicked submit button and same is updated in database.So while i am reloading the
page i am comparing mango with apple, pineapple, mango,custard apple etc. If a match is found i am highlighting that value and the corresponding table should be displayed
The problem here is combo box value and list box value is first displayed and then it takes few seconds to display the Table which looks very awkward for the end user.
Below is the coding which i have done....

JavaScript:
  1. for(optionId=0, key=1, value=0; optionId <maxEntityCount; optionId++){
  2.  document.form1.listbox.options[optionId] = new Option(fruitsArray[key],fruitsArray[value]);
  3.   if(typesoffruits == fruitsArray[key])[html]
  4.   {
  5.     document.form1.listbox.options[optionId].selected = true;
  6.     isSelected = true
  7.   }
  8.   value=value+2;
  9.   key=key+2;
  10. }
  11.  
  12. if(isSelected == true){
  13.   loadtable();
  14. }

I want to know whether there is any way in java script such that without iterating the loop i should able to highlight the value which i got from database and the corresponding table should be loaded. That is without iterating typesoffruits with fruitsArray i must able to highlight the typesoffruits and its table should be displayed.

Thanks for patiently reading such a long mail..
Thanks for your efforts and response.[/html]

What it sounds like you're looking for here is actually pretty simple to accomplish. You're keying on the key here, and if you've got the relationship set up the same way in the select element, you can very easily set them to be selected with the following code:

JavaScript:
  1. /*
  2.    if "mango" is selected, and has an id of 1, we assume
  3.    that the option in the list box is going to look like this:
  4.    <option value="1">Mango</option>
  5.   */
  6.   var elm = document.forms['form1']['listbox'];
  7.   elm.options[1].select = true;

Keep in mind, however, that in order for this to work, you must have the elements in the select element ordered by the key, and not alphabetically.

So you'd need to have:

HTML:
  1. <select name="listbox">
  2.   <option value="0">Select</option>
  3.   <option value="1">Mango</option>
  4.   etc...
  5. </select>

Without more information, that's the best answer I can provide. If you'd like to submit the code for review and adjustment, please feel free.

Comments always welcome!
Anthony

Followup 2/5/2008:

Thanks Anthony for you very valuable suggestion and help. That code is working fine. I am having one more query ...
How can i get the multiple selected values from lIst box using Java script.

Example: Consider i have mango, apple, grapes,strawberry in a listbox.
I am selecting apple and grapes and on click of submit button I am calling a javascript method called getFruits(). In that method, how can i get the selected values i.e(apple and grapes).

Thanks and Regards

This is fairly simple as well. Hat tip goes to DigitialAmit.com, where I picked up this nifty little snippet that does precisely what you need.

JavaScript:
  1. var arSelected = [];
  2.  
  3. function getMultiple(ob) {
  4.   while (ob.selectedIndex != -1) {
  5.     if (ob.selectedIndex != 0) {
  6.       arSelected.push(ob.options[ob.selectedIndex].value);
  7.     }
  8.      ob.options[ob.selectedIndex].selected = false;
  9.    } // You can use the arSelected array for further processing.
  10. }

Which will get all of the selected items and then deselect them. If you wanted to re-select them after you did the collection, you could simply loop through your arSelected array and set them to selected again.

All the best,
Anthony
price oem soft Wordpress Wordpress CMS

Dynamic Tables: IE vs Everyone Else

I just came off a full day fighting with a dynamic table addition, and I thought I'd go ahead and save someone else the pain.

I have a table, and I want to add rows via JavaScript when the user clicks a button. I created a function that did this. Since I develop against FireFox, I usually cross my fingers, load in IE for testing, and hope for the best.

Well, hope is, as they say, as hollow as fear.

the following function worked in FF, Opera, and Safari

JavaScript:
  1. function addRow() {
  2.   var tbl = document.getElementById('mytable');
  3.   var row = document.createElement("tr");
  4.   var td = document.createElement("td");
  5.   var input = document.createElement('input');
  6.  
  7.   td.appendChild(input);
  8.   row.appendChild(td);
  9.   tbl.appendChild(row);
  10. }

This created a new row in my table in FireFox and the like with a textfield in it. I've stripped out a lot of the extraneous properties and such, although I did add an onkeypress event to the field, twelve different fields, two select elements, and three text nodes.
Then I ran it in IE7, and nothing happened when I clicked the button. Or so it seemed. When I posted the form these were contained in, the new fields were there in the POST array, but nothing appeared on the screen.

After spending hours upon hours puzzling, googling, and trying different things, I found this:

http://msdn2.microsoft.com/en-us/library/ms532998.aspx

Which basically tells you what I am about to, but they do it in more detail. IE7 exposes a TOM (Table Object Model) that allows you to do what I wanted to very easily, except that the TOM doesn't work in any other browser. They also offer a standard DOM methodology, which is what my problem was. Here's the code that works in both IE and FireFox (untested in the others):

JavaScript:
  1. function addRow() {
  2.  
  3.   var tbl = document.getElementById('mytable');
  4.   var tbody = document.createElement('tbody');
  5.   var row = document.createElement('tr');
  6.   var td = document.createElement('td');
  7.   var input = document.createElement('input');
  8.  
  9.   td.appendChild(input);
  10.   row.appendChild(td);
  11.   // Thanks to Keith over at Etheric Arts for pointing out this line had a typo:
  12.   // tbody.appendChild(td); (Oddly enough, Firefox will add the row for you, IE will not)
  13.  
  14.   // It should be:
  15.   tbody.appendChild(tr);
  16.  
  17.   tbl.appendChild(tbody);
  18. }

Hat-tip: Keith Moulton (Link:Etheric Arts)
See, the problem here was that I was adding a tr, td, and cell contents, but no tbody element to contain them. IE 7 was enforcing standards on me that FireFox and the others overlook.

While it was a frustrating lesson, it was a powerful one. Hope it helps someone else in need.

~A!

Who Should I be Mad at? IE or Firefox

It's funny, because when something "doesn't work" in IE7, I'm finding more and more it is because IE7 doesn't hold a developer's hand as much as FireFox 2 does. I'm maintaining several code bases I didn't write, so I want to see exactly what's wrong.

Developers who still want to put VBScript in their web pages, unbelievable though that may be, give me one headache after another. Here's a tip:

VBScript works in exactly one browser, Microsoft Internet Explorer. And it only works there for legacy support. No one is writing for a single browser any more. If you are using VBScript on the client side, stop. JavaScript is universally understood for the most part in all of the major browsers.

Right, so the page breaks in IE, because there's bad VBScript on the client side, but it doesn't break in Firefox, because FireFox ignores it. I'm a little disappointed that FireFox doesn't pop me some kind of error in the status window, javascript console, wherever, saying something like "Un-supported script type: VBScript on line {blah}".

Now, here's the part where things get hairy for IE. When you run IE7, script debugging is disabled by default. That makes a lot of sense, because this is a consumer product, after all, and not a development tool for the main base of its users. However, once you clear the checkbox for the script debugger (clearing the checkbox turns it on, isn't that intuitive?), you get an alert when there is a script error, and it asks you if you want to debug. If you don't have Visual Studio installed, and you don't have the Microsoft Script Debugger downloaded and installed, nothing happens.

I don't mean that it goes away with no message, I mean it acts as if I had never touched the button. I sit there clicking the button for a good fifteen seconds wondering what's happening, and then I realize "D'OH! I need to install the Microsoft Script Debugger!".

I can't upload the script debugger and link to it here, because of stupid Microsoft Genuine Advantage rules, but I can give you a link over to MS to download it yourself, always assuming you pass the Genuine Check.

(Ms Script Debugger Link)

Next time, I'll talk about the new Developer Toolbar for IE7. Does it measure up to the Firefox extension?

~A!

WordPress Themes