Friday, September 18, 2009 0 comments

Adding / Removing Options In A Combo Box

This JS function removed all options in a combo box except the first entry. If you want to remove the first entry as well then change the i>0 to i>=0

function removeExistingOptions(selBox){
       
       
          var i;
          for (i = selBox.length - 1; i>0; i--) {
              selBox.remove(i);
          }

}

The following function adds options to an existing combo box.

function addOptions(selBox){  

        var opt1=document.createElement('option');
        opt1.text='OPT1';
        opt1.value='OPT1';
       
        var opt2=document.createElement('option');
        opt2.text='OPT2';
        opt2.value='OPT2';

try
          {
            // standards compliant
            selBox.add(opt1,null);
            selBox.add(opt2,null);
         
          }
        catch(ex)
          {
            // IE only
            selBox.add(opt1);
            selBox.add(opt2);
                
          }

}

In both functions you have to pass the select element as the reference to the function.

0 comments

DOM Manipulation In Tables

I was playing around with DOM manipulations in html tables and i wanted to add and remove table rows dynamically. In the end with the help of W3C school i was able to come up with a solution. Below is what i came up with in the end.

                var msgDetailsTable = document.getElementById("msgTable");
                msgDetailsTable.deleteRow(1);
                var x = msgDetailsTable.insertRow(1);
                var y=x.insertCell(0);
                var z=x.insertCell(1);
                y.width="20%";
                z.width="80%"
                y.innerHTML="<font>    Line  :</font>";
                z.innerHTML="<textarea rows='4' cols='100' id='msgTxtArea' name='msgTxtArea' readonly='readonly'></textarea>";

This deletes the second row and then adds two new different <td> elements setting its widths as appropriate. This will work on Fire fox 1.5+ and all IE browsers.
               

 
;