calculating in table made by createElement and appendChild

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • kie

    calculating in table made by createElement and appendChild

    hello,

    i have a table that creates and deletes rows dynamically using
    createElement, appendChild, removeChild.
    when i have added the required amount of rows and input my data, i
    would like to calculate the totals in each row.

    when i try however, i receive the error:

    "Error: 'elements[...]' is null or not an object"

    i have tried looping through all elements in the form and this gives
    me the name & value of each element.
    when i call the element by name however, i receive the above error.

    it is easier to explain by cuting and pasting the source of my html
    file below:

    i'd greatly appreciate any pointers, here's the code.


    <script language="JavaS cript" type="text/JavaScript" >
    <!--

    var InternetExplore r = navigator.appNa me.indexOf("Mic rosoft") != -1;
    var globalChanged = false;
    var globalNewRowCha nged = false;
    var globalClaimLnsR owNum = 1;

    function ex_amount(s_cur ){
    switch (s_cur)
    {
    case '1':
    return '1.2';
    break;
    case '2':
    return '0.6';
    break;
    case '3':
    return '1.5';
    break;
    case '4':
    return '2';
    break;
    case '5':
    return '1';
    break;
    default:
    return 0;
    }
    }

    function detail_row(s_go ods_id,s_unit_p rice,s_currency _id,s_quantity, s_uplift,s_tota l_line,s_incl_u plift,s_incl_up lift_euro)
    {
    var body=document.b ody;
    var Table,theRow,aC ell,aTextBox,ta blebody2,rowSec 2;
    var theTable;
    var rowSec1,current text;
    var opt1,sel2;
    var cellSec1,cellSe c2,cellSec3,cel lSec4,cellSec5;
    var cellSec6,cellSe c7,cellSec8,cel lSec9,cellSec10 ;
    theTable=docume nt.getElementBy Id('formation') .getElementsByT agName('tbody')[0];
    tablebody2 = document.create Element('TBODY' );
    rowSec2=documen t.createElement ('TR');
    cellSec2=docume nt.createElemen t('TD');
    sel2=document.c reateElement('s elect');
    sel2.name='2d_c mb_goods__' + globalClaimLnsR owNum;
    opt1=document.c reateElement('o ption');
    opt1.value='9';
    if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',
    true);}
    opt1.innerHTML= 'Airconditioner s';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='5';
    if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',
    true);}
    opt1.innerHTML= 'Audio Goods';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='13' ;
    if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',
    true);}
    opt1.innerHTML= 'Video Recorder';
    sel2.appendChil d(opt1);
    cellSec2.append Child(sel2);
    rowSec2.appendC hild(cellSec2);

    cellSec3=docume nt.createElemen t('TD');
    aTextBox=docume nt.createElemen t('input');
    aTextBox.type = 'text';
    aTextBox.value = nz(s_unit_price );
    aTextBox.size = '10';
    aTextBox.name = '2d_txt_unit_pr ice__' + globalClaimLnsR owNum;
    cellSec3.append Child(aTextBox) ;
    rowSec2.appendC hild(cellSec3);

    cellSec4=docume nt.createElemen t('TD');
    sel2=document.c reateElement('s elect');
    sel2.name='2d_c mb_currency__' + globalClaimLnsR owNum;
    opt1=document.c reateElement('o ption');
    opt1.value='1';
    if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',
    true);}
    opt1.innerHTML= 'US$';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='2';
    if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',
    true);}
    opt1.innerHTML= '」STG';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='3';
    if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',
    true);}
    opt1.innerHTML= 'A$';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='4';
    if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',
    true);}
    opt1.innerHTML= 'NZ$';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='5';
    if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',
    true);}
    opt1.innerHTML= 'BHAT';
    sel2.appendChil d(opt1);
    cellSec4.append Child(sel2);
    rowSec2.appendC hild(cellSec4);

    cellSec5=docume nt.createElemen t('TD');
    aTextBox=docume nt.createElemen t('input');
    aTextBox.type = 'text';
    aTextBox.value = nz(s_quantity);
    aTextBox.size = '5';
    aTextBox.name = '2d_txt_quantit y__' + globalClaimLnsR owNum;
    cellSec5.append Child(aTextBox) ;
    rowSec2.appendC hild(cellSec5);

    cellSec6=docume nt.createElemen t('TD');
    aTextBox=docume nt.createElemen t('input');
    aTextBox.type = 'text';
    aTextBox.value = nz(s_total_line );
    aTextBox.size = '5';
    aTextBox.name = '2d_txt_total_l ine__' + globalClaimLnsR owNum;
    cellSec6.append Child(aTextBox) ;
    rowSec2.appendC hild(cellSec6);

    cellSec7=docume nt.createElemen t('TD');
    sel2=document.c reateElement('s elect');
    sel2.name='2d_c mb_uplift__' + globalClaimLnsR owNum;
    opt1=document.c reateElement('o ption');
    opt1.value='100 ';
    if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
    opt1.innerHTML= '100%';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='105 ';
    if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
    opt1.innerHTML= '105%';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='110 ';
    if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
    opt1.innerHTML= '110%';
    sel2.appendChil d(opt1);
    opt1=document.c reateElement('o ption');
    opt1.value='0';
    if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
    opt1.innerHTML= 'other';
    sel2.appendChil d(opt1);
    cellSec7.append Child(sel2);
    rowSec2.appendC hild(cellSec7);

    cellSec8=docume nt.createElemen t('TD');
    aTextBox=docume nt.createElemen t('input');
    aTextBox.type = 'text';
    aTextBox.value = nz(s_incl_uplif t);
    aTextBox.size = '3';
    aTextBox.name = '2d_txt_incl_up lift__' + globalClaimLnsR owNum;
    cellSec8.append Child(aTextBox) ;
    rowSec2.appendC hild(cellSec8);

    cellSec9=docume nt.createElemen t('TD');
    aTextBox=docume nt.createElemen t('input');
    aTextBox.type = 'text';
    aTextBox.value = nz(s_incl_uplif t_euro);
    aTextBox.name = '2d_txt_incl_up lift_euro__' +
    globalClaimLnsR owNum;
    aTextBox.size = '5';
    aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
    cellSec9.append Child(aTextBox) ;
    rowSec2.appendC hild(cellSec9);

    cellSec10=docum ent.createEleme nt('TD');
    ButtonSupprimer =document.creat eElement('input ');
    ButtonSupprimer .type = 'button';
    ButtonSupprimer .value = 'remove';
    ButtonSupprimer .onclick=functi on(){formation. removeChild(tab lebody2)}
    cellSec10.appen dChild(ButtonSu pprimer);
    rowSec2.appendC hild(cellSec10) ;

    tablebody2.appe ndChild(rowSec2 );
    formation.appen dChild(tablebod y2);
    globalClaimLnsR owNum = globalClaimLnsR owNum + 1;
    }

    function calculateTab(n_ line_no){

    var oForm = document.forms[0];

    alert('line number = ' + n_line_no);

    oForm.elements['2d_txt_total_l ine__' + n_line_no].value =
    nz(oForm.elemen ts['2d_txt_unit_pr ice__' + n_line_no].value) *
    nz(oForm.elemen ts['2d_txt_quantit y__' + n_line_no].value);
    }

    function nz(s_val){
    var s_datatype = "undefined" ;
    if(s_val==null || s_val=='' || isNaN(s_val) ||
    typeof(s_val)== s_datatype){
    //return isNaN(num)?0:nu m;
    return 0;
    }
    else{
    //alert(s_val);
    return parseFloat(s_va l);
    }
    }

    function resetForm(){
    var oForm = document.forms[0];
    for (i=0; i<oForm.element s.length; i++){
    oForm.elements[i].value = "";
    }
    }

    function setLabel(s_mess age,s_label_nam e) {
    document.all(s_ label_name).inn erText = s_message;
    }
    //-->
    </script>

    <html>
    <head>
    </head>
    <body>
    <form method="post" action="" id="form1" name="form1">
    <table>
    <tr>
    <td width='4%'>
    <tr>
    <td colspan='6'> </td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td><input type="button" name="Button2" value="change label"
    onclick=setlabe l('here is some different text','label_de tail');>
    </td>
    <td><input type="button" name="Button" value="calculat e"
    onclick=calcula teTab('1');></td>
    <td colspan='1' align='right'>& nbsp;</td>
    <td>
    <input name='cmd_detai l_new' type='button' id='cmd_detail_ new'
    value='add row [click here]' onclick=detail_ row();>
    </td>
    <td>&nbsp;</td>
    <td colspan='3' align='right'>t otal </td>
    <td>
    <input name='2d_txt_de tail_total' type='text'
    id='2d_txt_deta il_total' value='' size='10'
    onChange=docume nt.forms[0].elements['txt_haschanged '].value ='yes';>
    </td>
    <td width='16%'>=EU R</td>
    <td width='30%'>
    <input name='2d_txt_de tail_total_euro ' type='text'
    id='2d_txt_deta il_total_euro' value='' size='10'
    onChange=docume nt.forms[0].elements['txt_haschanged '].value
    ='yes';></td>
    </td>
    </tr>
    <tr>
    <td colspan='6'></td>
    </tr>
    </table>
    </td>
    </tr>
    </table>


    <table>
    <tr>
    <td height='20' valign='top'>
    <table width='100%' border='1' cellpadding='0' cellspacing='0'
    valign='top' id='formation'>
    <tr>
    <td width='15%'>&nb sp;<b>GOODS</b></td>
    <td width='5%'>&nbs p;<b>UNIT PRICE</b></td>
    <td width='10%'>&nb sp;<b>CURRENCY</b></td>
    <td width='5%'>&nbs p;<b>QUANTITY</b></td>
    <td width='5%'>&nbs p;<b>TOTAL LINE</b></td>
    <td width='5%'>&nbs p;<b>UPLIFT (%)</b></td>
    <td width='5%'>&nbs p;<b>INCL. UPLIFT</b></td>
    <td width='5%'>&nbs p;<b>=EUR</b></td>
    <td width='5%'>&nbs p;<b>&nbsp;</b></td>
    </tr>
    <tr>
    <td colspan='10'>
    <label id='label_detai l'>NO RECORDS FOUND</label>
    </td>
    </tr>
    <input type='text' id='2d_txt_deta il_ids'
    name='2d_txt_de tail_ids' value=''>
    <input type='text' id='txt_update_ ids' name='txt_updat e_ids'
    value=''>
    </table> </td>
    </tr>
    </table>
    </form>
    </body>
    </html>


    thanks for any help, kie

    p.s. the funtion setLabel that addresses: <label id='label_detai l'>
    fails for a reason unknown to me, any pointers on this too would be
    greatly appreciated.
  • Dom Leonard

    #2
    Re: calculating in table made by createElement and appendChild

    kie wrote:
    [color=blue]
    > i have a table that creates and deletes rows dynamically using
    > createElement, appendChild, removeChild.
    > when i have added the required amount of rows and input my data, i
    > would like to calculate the totals in each row.
    >
    > when i try however, i receive the error:
    >
    > "Error: 'elements[...]' is null or not an object"
    >
    > i have tried looping through all elements in the form and this gives
    > me the name & value of each element.
    > when i call the element by name however, i receive the above error.
    >
    > it is easier to explain by cuting and pasting the source of my html
    > file below:
    >
    > i'd greatly appreciate any pointers, here's the code.
    >[/color]
    <snip>

    hi Kie,
    had a look and wrote down things as I encountered them. IE bug looks
    like the biggest problem:

    HTML:
    Generally include script elements in the head section or (less often) in
    the body section.
    (moved script to head section when testing)

    Element names beginning with "2d" are invalid HTML:
    <cite>
    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
    followed by any number of letters, digits ([0-9]), hyphens ("-"),
    underscores ("_"), colons (":"), and periods (".").
    </cite>
    (low priority in that it works in some browsers. Changed "2d" to "Two_d"
    when testing)


    Handler text used in HTML attribute values should be quoted
    <cite>
    In certain cases, authors may specify the value of an attribute without
    any quotation marks. The attribute value may only contain letters (a-z
    and A-Z), digits (0-9), hyphens (ASCII decimal 45), periods (ASCII
    decimal 46), underscores (ASCII decimal 95), and colons (ASCII decimal
    58). We recommend using quotation marks even when it is possible to
    eliminate them.
    </cite>
    This rules out most javascript code.
    (low priority in that it works in some browsers. Didn't change during test)



    DOM errors:
    To access elements by id, use document.getEle mentById.
    Access using named properties of the window object is not standard.
    Hence changed

    theTable=docume nt.getElementBy Id('formation') .getElementsByT agName('tbody')[0];
    to
    var formation = document.getEle mentById('forma tion');
    theTable=format ion.getElements ByTagName('tbod y')[0];
    in order to allow later event handlers to access the formation value
    held in the closure.
    [This may set up memory leaks under IE. Walking the DOM in an
    unbeforeunload handler and setting event handlers to null is one
    possible workaround, although changing use of formation to
    getElementById( 'formation') may be a better idea.]

    Also changed setLabel use of document.all to document.getEle mentById.
    Note that innerText is not a standard method of altering the text
    content of element nodes. This has been covered in other posts with
    bodies containing "createTextNode ". Even "innerHTML" is more cross
    browser compliant.
    function setLabel(s_mess age,s_label_nam e) {
    document.getEle mentById(s_labe l_name).innerHT ML = s_message;
    }
    tested.

    (priority for WWW documents)


    Browser Detection
    IE conditional comments can reliably check for Internet Explorer
    (from Lasse Reichstein Nielsen, 27/9/03)

    <script type="text/javascript">
    var isIE = false;
    </script>
    <!--[if IE]>
    <script type="text/javascript">
    isIE = true;
    </script>
    <!--[end if]-->

    Internet Explorer Bug
    This is the killer. Form field elements added to the DOM are not
    reflected as named properties of the FORM object. Code fix after adding
    elements and before accessing them by name:

    function makeFieldUnionB yName(oEls, name)
    {
    var result = null;
    var resultArray = false;
    for( var i = 0; i < oEls.length; ++i)
    {
    if( oEls[i].name!=name)
    continue;
    if( result && !resultArray)
    { result = [result];
    resultArray = true;
    }
    if(resultArray)
    result[result.length]=oEls[i];
    else
    result=oEls[i];
    }
    return result;
    }
    function fixFormBug( oForm) // Internet Explorer only
    {
    var oEls = oForm.elements;
    var name;
    for( var i = 0; i < oEls.length; ++i)
    {
    name = oEls[i].name;
    if(name && !oForm[ name])
    oForm[name] = makeFieldUnionB yName(oEls,name );
    }
    }
    /* ....
    and then in calculateTab
    ...
    */
    var oForm = document.forms[0];
    if(isIE)
    fixFormBug( oForm)
    ...

    Case Sensitivity
    call setLabel using the same combination of case.
    onchange="setLa bel(....)"

    ========
    HTH
    Dom



    Comment

    • kie

      #3
      Re: calculating in table made by createElement and appendChild

      wow! Dom, that really helped me a lot.

      what you said made sense and i can now calculate all the rows after
      updating each cell. this is what i set out to do.

      to increase efficiency i tried to calculate each row individually,
      using the line: "aTextBox.oncha nge=function(){ calculateTab(gl obalClaimLnsRow Num);}"
      to send the current row number to the calculateTab function.
      globalClaimLnsR owNum is a global variable though, so the value in
      calculateTab is always the maximum value of globalClaimLnsR owNum. is
      there a way to calculate a single row?

      copy and pasting the below code will present an example, it also shows
      dom's solutions in practice:

      <html>
      <head>
      <script language="JavaS cript" type="text/JavaScript" >
      <!--

      var InternetExplore r = navigator.appNa me.indexOf("Mic rosoft") != -1;
      var globalChanged = false;
      var globalNewRowCha nged = false;
      var globalClaimLnsR owNum = 1;
      var isIE = false;
      // make check - find IE = true.
      isIE = true;

      function ex_amount(s_cur ){
      switch (s_cur)
      {
      case '1':
      return '1.2';
      break;
      case '2':
      return '0.6';
      break;
      case '3':
      return '1.5';
      break;
      case '4':
      return '2';
      break;
      case '5':
      return '1';
      break;
      default:
      return 0;
      }
      }

      function detail_row(s_go ods_id,s_unit_p rice,s_currency _id,s_quantity, s_uplift,s_tota l_line,s_incl_u plift,s_incl_up lift_euro)
      {
      var body=document.b ody;
      var Table,theRow,aC ell,aTextBox,ta blebody2,rowSec 2;
      var theTable;
      var rowSec1,current text;
      var opt1,sel2;
      var cellSec1,cellSe c2,cellSec3,cel lSec4,cellSec5;
      var cellSec6,cellSe c7,cellSec8,cel lSec9,cellSec10 ;
      var formation = document.getEle mentById('forma tion');
      theTable=format ion.getElements ByTagName('tbod y')[0];

      tablebody2 = document.create Element('TBODY' );
      rowSec2=documen t.createElement ('TR');
      cellSec2=docume nt.createElemen t('TD');
      sel2=document.c reateElement('s elect');
      sel2.name='two_ d_cmb_goods__' + globalClaimLnsR owNum;
      sel2.onchange=f unction(){calcu lateTab(globalC laimLnsRowNum); }
      opt1=document.c reateElement('o ption');
      opt1.value='9';
      if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',true); }
      opt1.innerHTML= 'Airconditioner s';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='5';
      if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',true); }
      opt1.innerHTML= 'Audio Goods';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='13' ;
      if (opt1.value==s_ goods_id){opt1. setAttribute('s elected',true); }
      opt1.innerHTML= 'Video Recorder';
      sel2.appendChil d(opt1);
      cellSec2.append Child(sel2);
      rowSec2.appendC hild(cellSec2);

      cellSec3=docume nt.createElemen t('TD');
      aTextBox=docume nt.createElemen t('input');
      aTextBox.type = 'text';
      aTextBox.value = nz(s_unit_price );
      aTextBox.size = '10';
      aTextBox.name = 'two_d_txt_unit _price__' + globalClaimLnsR owNum;
      aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
      cellSec3.append Child(aTextBox) ;
      rowSec2.appendC hild(cellSec3);

      cellSec4=docume nt.createElemen t('TD');
      sel2=document.c reateElement('s elect');
      sel2.name='two_ d_cmb_currency_ _' + globalClaimLnsR owNum;
      sel2.onchange=f unction(){calcu lateTab(globalC laimLnsRowNum); }
      opt1=document.c reateElement('o ption');
      opt1.value='1';
      if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',tru e);}
      opt1.innerHTML= 'US$';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='2';
      if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',tru e);}
      opt1.innerHTML= '」STG';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='3';
      if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',tru e);}
      opt1.innerHTML= 'A$';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='4';
      if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',tru e);}
      opt1.innerHTML= 'NZ$';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='5';
      if (opt1.value==s_ currency_id){op t1.setAttribute ('selected',tru e);}
      opt1.innerHTML= 'BHAT';
      sel2.appendChil d(opt1);
      cellSec4.append Child(sel2);
      rowSec2.appendC hild(cellSec4);

      cellSec5=docume nt.createElemen t('TD');
      aTextBox=docume nt.createElemen t('input');
      aTextBox.type = 'text';
      aTextBox.value = nz(s_quantity);
      aTextBox.size = '5';
      aTextBox.name = 'two_d_txt_quan tity__' + globalClaimLnsR owNum;
      aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
      cellSec5.append Child(aTextBox) ;
      rowSec2.appendC hild(cellSec5);

      cellSec6=docume nt.createElemen t('TD');
      aTextBox=docume nt.createElemen t('input');
      aTextBox.type = 'text';
      aTextBox.value = nz(s_total_line );
      aTextBox.size = '5';
      aTextBox.name = 'two_d_txt_tota l_line__' + globalClaimLnsR owNum;
      aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
      cellSec6.append Child(aTextBox) ;
      rowSec2.appendC hild(cellSec6);

      cellSec7=docume nt.createElemen t('TD');
      sel2=document.c reateElement('s elect');
      sel2.name='two_ d_cmb_uplift__' + globalClaimLnsR owNum;
      sel2.onchange=f unction(){calcu lateTab(globalC laimLnsRowNum); }
      opt1=document.c reateElement('o ption');
      opt1.value='100 ';
      if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
      opt1.innerHTML= '100%';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='105 ';
      if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
      opt1.innerHTML= '105%';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='110 ';
      if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
      opt1.innerHTML= '110%';
      sel2.appendChil d(opt1);
      opt1=document.c reateElement('o ption');
      opt1.value='0';
      if (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
      opt1.innerHTML= 'other';
      sel2.appendChil d(opt1);
      cellSec7.append Child(sel2);
      rowSec2.appendC hild(cellSec7);

      cellSec8=docume nt.createElemen t('TD');
      aTextBox=docume nt.createElemen t('input');
      aTextBox.type = 'text';
      aTextBox.value = nz(s_incl_uplif t);
      aTextBox.size = '3';
      aTextBox.name = 'two_d_txt_incl _uplift__' +
      globalClaimLnsR owNum;
      aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
      cellSec8.append Child(aTextBox) ;
      rowSec2.appendC hild(cellSec8);

      cellSec9=docume nt.createElemen t('TD');
      aTextBox=docume nt.createElemen t('input');
      aTextBox.type = 'text';
      aTextBox.value = nz(s_incl_uplif t_euro);
      aTextBox.name = 'two_d_txt_incl _uplift_euro__' +
      globalClaimLnsR owNum;
      aTextBox.size = '5';
      aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}
      cellSec9.append Child(aTextBox) ;
      rowSec2.appendC hild(cellSec9);

      cellSec10=docum ent.createEleme nt('TD');
      ButtonSupprimer =document.creat eElement('input ');
      ButtonSupprimer .type = 'button';
      ButtonSupprimer .value = 'remove';
      ButtonSupprimer .onclick=functi on(){formation. removeChild(tab lebody2)}
      cellSec10.appen dChild(ButtonSu pprimer);
      rowSec2.appendC hild(cellSec10) ;

      tablebody2.appe ndChild(rowSec2 );
      formation.appen dChild(tablebod y2);
      globalClaimLnsR owNum = globalClaimLnsR owNum + 1;
      }

      function calculateTab(n_ line_no){

      alert(n_line_no );

      var oForm = document.forms[0];
      var a_ids = new Array;
      var j=0;
      var s_cur = 0;
      var n_uplift = 0;
      var n_uplift_euro = 0;

      if(isIE)
      fixFormBug( oForm)

      // make array of ids were dealing with
      for (i=0; i<oForm.element s.length; i++){
      if(oForm.elemen ts[i].name.indexOf(" two_d_") == 0){
      if(oForm.elemen ts[i].name.indexOf(" two_d_cmb_goods __") == 0){
      n = oForm.elements[i].name.replace(/two_d_cmb_goods __/g,'');
      a_ids[j] = n;
      j = j+1;
      }
      }
      }

      // use array of ids to calculate all values in all rows
      for (i=0; i<j; i++){
      oForm.elements['two_d_txt_tota l_line__' + a_ids[i]].value =
      (parseFloat(nz( oForm.elements['two_d_txt_unit _price__' +
      a_ids[i]].value)) * parseFloat(nz(o Form.elements['two_d_txt_quan tity__'
      + a_ids[i]].value)));
      oForm.elements['two_d_txt_incl _uplift__' + a_ids[i]].value =
      (parseFloat(nz( oForm.elements['two_d_txt_tota l_line__' +
      a_ids[i]].value)) * (parseFloat(nz( oForm.elements['two_d_cmb_upli ft__'
      + a_ids[i]].value))/100));
      oForm.elements['two_d_txt_incl _uplift_euro__' + a_ids[i]].value =
      (parseFloat(oFo rm.elements['two_d_txt_incl _uplift__' +
      a_ids[i]].value) * (ex_amount(oFor m.elements['two_d_cmb_curr ency__' +
      a_ids[i]].value)));
      n_uplift = n_uplift + nz(oForm.elemen ts['two_d_txt_incl _uplift__' +
      a_ids[i]].value);
      n_uplift_euro = n_uplift_euro +
      nz(oForm.elemen ts['two_d_txt_incl _uplift_euro__' + a_ids[i]].value);
      }

      // if currencies are not all equal, cannot show sum of incl. uplift,
      only sum of euro
      for (i=0; i<j; i++){
      if((s_cur != oForm.elements['two_d_cmb_curr ency__' +
      a_ids[i]].value) & (s_cur != 0)){
      n_uplift = 0
      break;
      }
      s_cur = oForm.elements['two_d_cmb_curr ency__' + a_ids[i]].value;
      }

      // assign total values
      oForm.elements['two_d_txt_deta il_total'].value = nz(n_uplift);
      oForm.elements['two_d_txt_deta il_total_euro'].value =
      nz(n_uplift_eur o);

      }

      function nz(s_val){
      var s_datatype = "undefined" ;
      if(s_val==null || s_val=='' || isNaN(s_val) ||
      typeof(s_val)== s_datatype){
      //return isNaN(num)?0:nu m;
      return 0;
      }
      else{
      //alert(s_val);
      return parseFloat(s_va l);
      }
      }

      function resetForm(){
      var oForm = document.forms[0];
      for (i=0; i<oForm.element s.length; i++){
      oForm.elements[i].value = "";
      }
      }

      function setLabel(s_mess age,s_label_nam e) {
      document.getEle mentById(s_labe l_name).innerHT ML = s_message;
      }


      function makeFieldUnionB yName(oEls, name)
      {
      var result = null;
      var resultArray = false;
      for( var i = 0; i < oEls.length; ++i)
      {
      if( oEls[i].name!=name)
      continue;
      if( result && !resultArray)
      { result = [result];
      resultArray = true;
      }
      if(resultArray)
      result[result.length]=oEls[i];
      else
      result=oEls[i];
      }
      return result;
      }
      function fixFormBug( oForm) // Internet Explorer only
      {
      var oEls = oForm.elements;
      var name;
      for( var i = 0; i < oEls.length; ++i)
      {
      name = oEls[i].name;
      if(name && !oForm[ name])
      oForm[name] = makeFieldUnionB yName(oEls,name );
      }
      }


      //-->
      </script>

      </head>
      <body>
      <form method="post" action="" id="form1" name="form1">
      <table>
      <tr>
      <td width='4%'>
      <tr>
      <td colspan='6'> </td>
      </tr>
      <tr>
      <td>&nbsp;</td>
      <td><input type='button' name='Button2' value='change label'
      onclick=setLabe l('','label_det ail');>
      </td>
      <td><input type="button" name="Button" value="calculat e"
      onclick=calcula teTab(1);></td>
      <td colspan='1' align='right'>& nbsp;</td>
      <td>
      <input name='cmd_detai l_new' type='button' id='cmd_detail_ new'
      value='add row [click here]'
      onclick=detail_ row();setLabel( '','label_detai l');>
      </td>
      <td>&nbsp;</td>
      <td colspan='3' align='right'>t otal </td>
      <td>
      <input name='two_d_txt _detail_total' type='text'
      id='two_d_txt_d etail_total' value='' size='10'
      onChange=docume nt.forms[0].elements['txt_haschanged '].value ='yes';>
      </td>
      <td width='16%'>=EU R</td>
      <td width='30%'>
      <input name='two_d_txt _detail_total_e uro'
      type='text'id=' two_d_txt_detai l_total_euro' value='' size='10'
      onChange=docume nt.forms[0].elements['txt_haschanged '].value='yes';></td>
      </td>
      </tr>
      <tr>
      <td colspan='6'></td>
      </tr>
      </table>
      </td>
      </tr>
      </table>


      <table>
      <tr>
      <td height='20' valign='top'>
      <table width='100%' border='1' cellpadding='0' cellspacing='0'
      valign='top' id='formation'>
      <tr>
      <td width='15%'>&nb sp;<b>GOODS</b></td>
      <td width='5%'>&nbs p;<b>UNIT PRICE</b></td>
      <td width='10%'>&nb sp;<b>CURRENCY</b></td>
      <td width='5%'>&nbs p;<b>QUANTITY</b></td>
      <td width='5%'>&nbs p;<b>TOTAL LINE</b></td>
      <td width='5%'>&nbs p;<b>UPLIFT (%)</b></td>
      <td width='5%'>&nbs p;<b>INCL. UPLIFT</b></td>
      <td width='5%'>&nbs p;<b>=EUR</b></td>
      <td width='5%'>&nbs p;<b>&nbsp;</b></td>
      </tr>
      <tr>
      <td colspan='10'>
      <label id="label_detai l">NO RECORDS FOUND</label>
      </td>
      </tr>
      <input type='text'
      id='two_d_txt_d etail_ids'name= 'two_d_txt_deta il_ids' value=''>
      <input type='text' id='txt_update_ ids' name='txt_updat e_ids'
      value=''>
      </table> </td>
      </tr>
      </table>
      </form>
      </body>
      </html>

      thanks for any help,

      kie

      Comment

      • Dom Leonard

        #4
        Re: calculating in table made by createElement and appendChild

        kie wrote:
        i can now calculate all the rows after[color=blue]
        > updating each cell. this is what i set out to do.
        >
        > to increase efficiency i tried to calculate each row individually,[/color]
        This might be useful, but be careful: if an existing row is changed, how
        to make certain page totals are updated correctly?
        [color=blue]
        > using the line: "aTextBox.oncha nge=function(){ calculateTab(gl obalClaimLnsRow Num);}"
        > to send the current row number to the calculateTab function.
        > globalClaimLnsR owNum is a global variable though, so the value in
        > calculateTab is always the maximum value of globalClaimLnsR owNum. is
        > there a way to calculate a single row?[/color]

        You could determine the row number of an element which has changed by
        assigning the TR in which it resides an id based on row number, and
        searching for the TR and its id in the parentNode chain of an element.

        After looking at the code further I noticed a few more things. For your
        own interest I suggest placing doctype and character set definitions:

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
        <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

        at the start of the document and validating it at:
        W3C's easy-to-use markup validation service, based on SGML and XML parsers.


        [color=blue]
        >
        > <html>
        > <head>
        > <script language="JavaS cript" type="text/JavaScript" >[/color]
        Note the language attribute is deprecated:
        <script type="text/javascript">[color=blue]
        > <!--[/color]
        SGML comments can be omitted nowadays (unless you use a validation tool
        that requires them)[color=blue]
        >
        > var InternetExplore r = navigator.appNa me.indexOf("Mic rosoft") != -1;[/color]
        This check is unreliable - apparently browsers forge the appName value
        on a regular basis.[color=blue]
        > var globalChanged = false;
        > var globalNewRowCha nged = false;
        > var globalClaimLnsR owNum = 1;
        > var isIE = false;
        > // make check - find IE = true.
        > isIE = true;[/color]

        uh huh :)
        Okay, the page is under development and the real test goes in later...

        <snip>

        All the event handlers in detail_row retain the activation object of
        detail_row() in scope and probably leak memory under IE6. I made some
        static functions to replace the nested function versions (not shown,
        they could go into a single object as properties to save on name space)

        function calculateAll()
        {
        calculateTab(gl obalClaimLnsRow Num);
        }

        function removeRow() // method of form element within row
        {
        for( var node = this.parentNode ; node; node=node.paren tNode)
        if(node.tagName =="TR")
        break;
        node.parentNode .removeChild(no de);
        calculateAll();
        }

        and in the editor replaced all
        function(){calc ulateTab(global ClaimLnsRowNum) ;}
        with
        calculateAll;

        Now comes the gritty bit. In the HTML code posted, you do not provide a
        TBODY element before accessing it in code (so the browser must supply
        it), and insert rows as TBODY elements. In testing, I inserted the
        missing TBODY tag and started inserting and deleting TR elements, so a
        few lines need changing:


        [color=blue]
        > function detail_row(s_go ods_id,s_unit_p rice,s_currency _id,s_quantity, s_uplift,s_tota l_line,s_incl_u plift,s_incl_up lift_euro)
        > {[/color]
        ....
        removed:[color=blue]
        > // theTable=format ion.getElements ByTagName('tbod y')[0];[/color]
        inserted:
        var tablebody2=form ation.getElemen tsByTagName('tb ody')[0];
        removed:[color=blue]
        > // tablebody2 = document.create Element('TBODY' );[/color]

        ....
        [color=blue]
        > aTextBox.onchan ge=function(){c alculateTab(glo balClaimLnsRowN um);}[/color]
        This is one of the lines changed to
        aTextBox.onchan ge=calculateAll ;

        ....

        Changed[color=blue]
        > ButtonSupprimer .onclick=functi on(){formation. removeChild(tab lebody2)}[/color]
        to
        ButtonSupprimer .onclick=remove Row;

        ....
        After[color=blue]
        > rowSec2.appendC hild(cellSec10) ;[/color]
        inserted:
        rowSec2.id = "row_" + globalClaimLnsR owNum;[color=blue]
        >[/color]
        and after[color=blue]
        > tablebody2.appe ndChild(rowSec2 );[/color]
        removed:[color=blue]
        > // formation.appen dChild(tablebod y2);[/color]

        ....[color=blue]
        > function fixFormBug( oForm) // Internet Explorer only[/color]

        [A cautionary note on this code fix. As written, it patches an IE form
        object after elements have been added, but makes no repairs if field
        elements have been removed. In this particular case that should be not
        be a problem, but would test submission][color=blue]
        >[/color]
        ....
        The BODY used in testing (with various fixups) was:

        <body>
        <form method="post" action="" id="form1" name="form1">

        <table>
        <tbody>
        <tr>
        <td>&nbsp;</td>
        <td>
        <input type='button' name='Button2' value='change label'
        onclick="setLab el('','label_de tail');">
        </td>
        <td>
        <input type="button" name="Button" value="calculat e"
        onclick="calcul ateTab(1);">
        </td>
        <td>&nbsp;</td>
        <td>
        <input name='cmd_detai l_new' type='button' id='cmd_detail_ new'
        value='add row [click here]'
        onclick="detail _row();setLabel ('','label_deta il');">
        </td>
        <td>&nbsp;</td>
        <td align='right'>t otal </td>
        <td>
        <input name='two_d_txt _detail_total' type='text'
        id='two_d_txt_d etail_total' value='' size='10'
        onchange="form. elements['txt_haschanged '].value ='yes';">
        </td>
        <td width='16%'>=EU R</td>
        <td width='30%'>
        <input name='two_d_txt _detail_total_e uro' type='text'
        id='two_d_txt_d etail_total_eur o' value='' size='10'
        onchange="form. elements['txt_haschanged '].value='yes';">
        </td>
        </tr>
        </tbody>
        </table>

        <!-- table in table removed, head and body elements inserted -->

        <table width='100%' border='1' cellpadding='0' cellspacing='0'
        valign='top' id='formation'>
        <thead>
        <tr>
        <td width='15%'>&nb sp;<b>GOODS</b></td>
        <td width='5%'>&nbs p;<b>UNIT PRICE</b></td>
        <td width='10%'>&nb sp;<b>CURRENCY</b></td>
        <td width='5%'>&nbs p;<b>QUANTITY</b></td>
        <td width='5%'>&nbs p;<b>TOTAL LINE</b></td>
        <td width='5%'>&nbs p;<b>UPLIFT (%)</b></td>
        <td width='5%'>&nbs p;<b>INCL. UPLIFT</b></td>
        <td width='5%'>&nbs p;<b>=EUR</b></td>
        <td width='5%'>&nbs p;<b>&nbsp;</b></td>
        </tr>
        <tr>
        <td colspan='9'>
        <label id="label_detai l">NO RECORDS FOUND</label>
        </td>
        </tr>

        <!-- insert missing TR, TD tags, put spaces between attributes -->

        <tr>
        <td colspan='9'>
        <input type='text' id='two_d_txt_d etail_ids'
        name='two_d_txt _detail_ids' value=''>
        <input type='text' id='txt_update_ ids'
        name='txt_updat e_ids' value=''>
        </td>
        </tr>
        </thead>

        <tbody><!-- empty at this stage -->
        </tbody>
        </table>
        </form>
        </body>

        ========

        Finally, if you want to find the row number from an event handler set on
        element within a row, walk up the DOM to find the TR element (similar to
        deleting a row) and extract the row number from the id value assigned in
        detail_row().

        HTH and good luck,
        Dom

        Comment

        • kie

          #5
          Re: calculating in table made by createElement and appendChild

          thanks for your advice Dom, you're making a lot of things clearer for
          me
          [color=blue]
          > After looking at the code further I noticed a few more things. For your
          > own interest I suggest placing doctype and character set definitions:
          >
          > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          > "http://www.w3.org/TR/html4/loose.dtd">
          > <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
          >
          > at the start of the document and validating it at:
          > http://validator.w3.org[/color]

          I have done this, one thing I noticed was that I couldn't control the
          size of my select boxes:

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
          <META http-equiv="Content-Type" content="text/html;
          charset=ISO-8859-1">
          <html>
          <head>
          <title>Untitl ed Document</title>
          </head>
          <body>
          <SELECT id='test' name='test' style='width:50 '>
          <OPTION name='select one' value='' selected>
          <OPTION name='1h_cmb_po licy' value='YY100018 78'>YY10001878
          <OPTION name='1h_cmb_po licy' value='YY100018 84'>YY10001884
          </OPTION>
          </SELECT>
          </body>
          </html>

          if I remove the first 2 lines from the code above, the select box will
          become 50 pixels in width.
          If I include the first 2 lines. the select box size is the width of
          the longest string contained in it.

          I tried adding the line:
          "sel2.style.wid th ='100';"

          after
          rowSec2.id = 'row_' + globalClaimLnsR owNum;
          cellSec2=docume nt.createElemen t('TD');
          and I had no problems.
          Are the style.width used in createElement and the style='width:50 ' in
          HTML much different commands?

          I've been studying the code you used to restrict a loop to one row; by
          copying the code from removeRow() into CalculateAll() I have tried and
          failed to extract the row number or "TR" id

          function calculateAll()
          {
          for( var node = this.parentNode ; node; node=node.paren tNode){
          //if(node.tagName =="TR"){
          //alert('node name and current row id: ' + node.Name);
          //alert('node name and current row id: ' +
          document.forms[0].elements.node. name);
          //alert('node name and current row id: ' +
          document.forms[0].elements[node].name);
          //alert('node name and current row id: ' + node);
          alert('node name and current row id: ' +
          document.getEle mentById(node)) ;
          // }
          }
          calculateTab(2, globalClaimLnsR owNum);
          }

          I would expect that if "node" is an object, then it should have a
          name. And I expected that name to be "row_1", "row_2" etc, from the
          line:

          "rowSec2.id = 'row_' + globalClaimLnsR owNum;"

          am I mistaking "node" for an "element"? I have changed the attributes
          of "TR" elements in the past using lines such as:

          "document.getEl ementById(tdId) .style.backgrou ndColor = '#000000';"

          With the "TBODY" element missing, the browser creates it. does that
          mean before i was unnecesasarily creating a new "TBODY" element each
          time the user clicks "Add Row"?
          Memory dissipation is also halted by calling a function instead of
          inserting the code into the elements onchange handler?

          I need to find out more about nodes, apart from that it works great,
          and is easier to understand now it is better laid out (below),

          thanks again,

          kie

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
          <META http-equiv="Content-Type" content="text/html;
          charset=ISO-8859-1">
          <html>
          <head>
          <meta name="Author" content="kie">
          <meta name="Copyright " content="2003">
          <meta name="keywords" content="">
          <meta name="descripti on" content="">
          <link rel="stylesheet " type="text/css"
          href="http://192.168.100.215/g-macs/lib/stylesheet.css" >
          <script>
          <!--
          // browser detection
          // "InternetExplor er = navigator.appNa me.indexOf("Mic rosoft") != -1;"
          // This check is unreliable - apparently browsers forge the appName
          value on a regular basis.
          //
          // checks should be made using the javascript that will be in the page
          for certain safety
          /**/
          var s_browser = "";
          // W3C & Netscape 6
          if(document.get ElementById) {
          s_browser = "netscape6" ;
          }
          // browser is IE 4+:
          else if (document.all) {
          s_browser = "ie4";
          }
          // browser is Netscape 4+:
          else if (document.layer s) {
          s_browser = "netscape4" ;
          }
          else {
          s_browser = "";
          }

          //-->
          </script>

          <script type="text/javaScript" >
          // JavaScript Document
          // lib/js_functions.js - contents:

          // setClaimID
          // AllCheck_onclic k
          // mWillSave
          // showHide
          //calculateTab(3) used to calculate values in individual pages esp.
          03_page.asp
          <!--

          var InternetExplore r = navigator.appNa me.indexOf("Mic rosoft") != -1;
          var globalChanged = false;
          var globalNewRowCha nged = false;
          var globalClaimLnsR owNum = 1;
          var isIE = false;

          isIE = true;

          function ex_amount(s_cur ){
          switch (s_cur)
          {
          case '1':
          return '1.2';
          break;
          case '2':
          return '0.6';
          break;
          case '3':
          return '1.5';
          break;
          case '4':
          return '2';
          break;
          case '5':
          return '1';
          break;
          default:
          return 0;
          }
          }

          function detail_row(s_go ods_id,s_unit_p rice,s_currency _id,s_quantity, s_uplift,s_tota l_line,s_incl_u plift,s_incl_up lift_euro)
          {
          var body=document.b ody;
          var Table,theRow,aC ell,aTextBox,ta blebody2,rowSec 2;
          var theTable;
          var rowSec1,current text;
          var opt1,sel2;
          var cellSec1,cellSe c2,cellSec3,cel lSec4,cellSec5;
          var cellSec6,cellSe c7,cellSec8,cel lSec9,cellSec10 ;
          var formation = document.getEle mentById('forma tion');
          var tablebody2=form ation.getElemen tsByTagName('tb ody')[0];
          rowSec1=documen t.createElement ('TR');
          cellSec1=docume nt.createElemen t('TD');
          currenttext=doc ument.createTex tNode('Intitul' );
          rowSec2=documen t.createElement ('TR');
          rowSec2.id = 'row_' + globalClaimLnsR owNum;
          cellSec2=docume nt.createElemen t('TD');
          sel2=document.c reateElement('s elect');
          sel2.style.widt h ='100';
          sel2.name='two_ d_cmb_goods__' +
          globalClaimLnsR owNum;
          sel2.onchange=c alculateAll;
          opt1=document.c reateElement('o ption');
          opt1.value='6';
          if
          (opt1.value==s_ goods_id){opt1. setAttribute('s elected', true);}
          opt1.innerHTML= 'Vacuum Cleaner';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='2';
          if
          (opt1.value==s_ goods_id){opt1. setAttribute('s elected', true);}
          opt1.innerHTML= 'Video Camera';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='1';
          if
          (opt1.value==s_ goods_id){opt1. setAttribute('s elected', true);}
          opt1.innerHTML= 'Video Recorder';
          sel2.appendChil d(opt1);
          cellSec2.append Child(sel2);
          rowSec2.appendC hild(cellSec2);

          cellSec3=docume nt.createElemen t('TD');
          aTextBox=docume nt.createElemen t('input');
          aTextBox.type = 'text';
          aTextBox.value = nz(s_unit_price );
          aTextBox.size = '10';
          aTextBox.name = 'two_d_txt_unit _price__' +
          globalClaimLnsR owNum;
          aTextBox.onchan ge=calculateAll ;
          cellSec3.append Child(aTextBox) ;
          rowSec2.appendC hild(cellSec3);

          cellSec4=docume nt.createElemen t('TD');
          sel2=document.c reateElement('s elect');
          sel2.name='two_ d_cmb_currency_ _' +
          globalClaimLnsR owNum;
          sel2.onchange=c alculateAll
          opt1=document.c reateElement('o ption');
          opt1.value='1';
          if
          (opt1.value==s_ currency_id){op t1.setAttribute ('selected', true);}
          opt1.innerHTML= 'US$';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='2';
          if
          (opt1.value==s_ currency_id){op t1.setAttribute ('selected', true);}
          opt1.innerHTML= '£STG';
          sel2.appendChil d(opt1);
          sel2.appendChil d(opt1);
          cellSec4.append Child(sel2);
          rowSec2.appendC hild(cellSec4);

          cellSec5=docume nt.createElemen t('TD');
          aTextBox=docume nt.createElemen t('input');
          aTextBox.type = 'text';
          aTextBox.value = nz(s_quantity);
          aTextBox.size = '5';
          aTextBox.name = 'two_d_txt_quan tity__' +
          globalClaimLnsR owNum;
          aTextBox.onchan ge=calculateAll
          cellSec5.append Child(aTextBox) ;
          rowSec2.appendC hild(cellSec5);

          cellSec6=docume nt.createElemen t('TD');
          aTextBox=docume nt.createElemen t('input');
          aTextBox.type = 'text';
          aTextBox.value = nz(s_total_line );
          aTextBox.size = '5';
          aTextBox.name = 'two_d_txt_tota l_line__' +
          globalClaimLnsR owNum;
          aTextBox.onchan ge=calculateAll
          cellSec6.append Child(aTextBox) ;
          rowSec2.appendC hild(cellSec6);

          cellSec7=docume nt.createElemen t('TD');
          sel2=document.c reateElement('s elect');
          sel2.name='two_ d_cmb_uplift__' +
          globalClaimLnsR owNum;
          sel2.onchange=f unction(){calcu lateTab(2,globa lClaimLnsRowNum );}
          opt1=document.c reateElement('o ption');
          opt1.value='100 ';
          if
          (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
          opt1.innerHTML= '100%';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='105 ';
          if
          (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
          opt1.innerHTML= '105%';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='110 ';
          if
          (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
          opt1.innerHTML= '110%';
          sel2.appendChil d(opt1);
          opt1=document.c reateElement('o ption');
          opt1.value='0';
          if
          (opt1.value==s_ uplift){opt1.se tAttribute('sel ected', true);}
          opt1.innerHTML= 'other';
          sel2.appendChil d(opt1);
          cellSec7.append Child(sel2);
          rowSec2.appendC hild(cellSec7);

          cellSec8=docume nt.createElemen t('TD');
          aTextBox=docume nt.createElemen t('input');
          aTextBox.type = 'text';
          aTextBox.value = nz(s_incl_uplif t);
          aTextBox.size = '3';
          aTextBox.name = 'two_d_txt_incl _uplift__' +
          globalClaimLnsR owNum;
          aTextBox.onchan ge=calculateAll
          cellSec8.append Child(aTextBox) ;
          rowSec2.appendC hild(cellSec8);

          cellSec9=docume nt.createElemen t('TD');
          aTextBox=docume nt.createElemen t('input');
          aTextBox.type = 'text';
          aTextBox.value = nz(s_incl_uplif t_euro);
          aTextBox.name = 'two_d_txt_incl _uplift_euro__' +
          globalClaimLnsR owNum;
          aTextBox.size = '5';
          aTextBox.onchan ge=calculateAll
          cellSec9.append Child(aTextBox) ;
          rowSec2.appendC hild(cellSec9);

          cellSec10=docum ent.createEleme nt('TD');
          ButtonSupprimer =document.creat eElement('input ');
          ButtonSupprimer .type = 'button';
          ButtonSupprimer .value = 'remove';
          ButtonSupprimer .onclick=remove Row;
          cellSec10.appen dChild(ButtonSu pprimer);
          rowSec2.appendC hild(cellSec10) ;
          tablebody2.appe ndChild(rowSec2 );
          formation.appen dChild(tablebod y2);
          globalClaimLnsR owNum = globalClaimLnsR owNum + 1;
          }

          function calculateTab(n_ tab_no,n_line_n o){

          var oForm = document.forms[0];
          var n;
          var t;
          var a_ids = new Array;
          var j=0;

          switch (n_tab_no)
          {
          case 1: // header
          break;
          case 2: // detail

          var s_cur = 0;
          var n_uplift = 0;
          var n_uplift_euro = 0;

          if(s_browser = "ie4"){
          fixFormBug(oFor m)
          }

          // make array of ids were dealing with
          for (i=0; i<oForm.element s.length; i++){
          if(oForm.elemen ts[i].name.indexOf(" two_d_") == 0){
          if(oForm.elemen ts[i].name.indexOf(" two_d_cmb_goods __") == 0){
          n = oForm.elements[i].name.replace(/two_d_cmb_goods __/g,'');
          a_ids[j] = n;
          j = j+1;
          }
          }
          }

          // use array of ids to calculate all values in all rows
          for (i=0; i<j; i++){
          //alert(n_tab_no+ ' ' +n_line_no + ' ' + a_ids[i]);
          oForm.elements['two_d_txt_tota l_line__' + a_ids[i]].value =
          (parseFloat(nz( oForm.elements['two_d_txt_unit _price__' +
          a_ids[i]].value)) * parseFloat(nz(o Form.elements['two_d_txt_quan tity__'
          + a_ids[i]].value)));
          oForm.elements['two_d_txt_incl _uplift__' + a_ids[i]].value =
          (parseFloat(nz( oForm.elements['two_d_txt_tota l_line__' +
          a_ids[i]].value)) * (parseFloat(nz( oForm.elements['two_d_cmb_upli ft__'
          + a_ids[i]].value))/100));
          oForm.elements['two_d_txt_incl _uplift_euro__' + a_ids[i]].value =
          (parseFloat(oFo rm.elements['two_d_txt_incl _uplift__' +
          a_ids[i]].value) * (ex_amount(oFor m.elements['two_d_cmb_curr ency__' +
          a_ids[i]].value)));
          n_uplift = n_uplift + nz(oForm.elemen ts['two_d_txt_incl _uplift__'
          + a_ids[i]].value);
          n_uplift_euro = n_uplift_euro +
          nz(oForm.elemen ts['two_d_txt_incl _uplift_euro__' + a_ids[i]].value);
          }

          // if currencies are not all equal, cannot show sum of incl.
          uplift, only sum of euro
          for (i=0; i<j; i++){
          if((s_cur != oForm.elements['two_d_cmb_curr ency__' +
          a_ids[i]].value) & (s_cur != 0)){
          n_uplift = 0
          break;
          }
          s_cur = oForm.elements['two_d_cmb_curr ency__' + a_ids[i]].value;
          }

          // assign total values
          oForm.elements['two_d_txt_deta il_total'].value = nz(n_uplift);
          oForm.elements['two_d_txt_deta il_total_euro'].value =
          nz(n_uplift_eur o);
          break;
          case 3: // pay rec
          break;
          case 4: // banking
          break;
          case 5: // p uk
          break;
          default:
          false;
          }
          }

          function makeFieldUnionB yName(oEls, name)
          {
          var result = null;
          var resultArray = false;
          for( var i = 0; i < oEls.length; ++i)
          {
          if( oEls[i].name!=name)
          continue;
          if( result && !resultArray)
          { result = [result];
          resultArray = true;
          }
          if(resultArray)
          result[result.length]=oEls[i];
          else
          result=oEls[i];
          }
          return result;
          }

          function fixFormBug(oFor m) // Internet Explorer only
          {
          var oEls = oForm.elements;
          var name;
          for( var i = 0; i < oEls.length; ++i)
          {
          name = oEls[i].name;
          if(name && !oForm[ name])
          oForm[name] = makeFieldUnionB yName(oEls,name );
          }
          }

          function calculateAll()
          {
          for( var node = this.parentNode ; node; node=node.paren tNode){
          //if(node.tagName =="TR"){
          //alert('node name and current row id: ' + node.Name);
          //alert('node name and current row id: ' +
          document.forms[0].elements.node. name);
          //alert('node name and current row id: ' +
          document.forms[0].elements[node].name);
          //alert('node name and current row id: ' + node);
          alert('node name and current row id: ' +
          document.getEle mentById(node)) ;
          // }
          }
          calculateTab(2, globalClaimLnsR owNum);
          }

          function removeRow() // method of form element within row
          {
          for( var node = this.parentNode ; node; node=node.paren tNode)
          if(node.tagName =="TR")
          break;
          node.parentNode .removeChild(no de);
          calculateAll();
          }


          function nz(s_val){
          var s_datatype = "undefined" ;
          if(s_val==null || s_val=='' || isNaN(s_val) ||
          typeof(s_val)== s_datatype){
          //return isNaN(num)?0:nu m;
          return 0;
          }
          else{
          //alert(s_val);
          return parseFloat(s_va l);
          }
          }

          function setLabel(object Id,s_label_name ,is_element) {
          if (is_element=='t rue'){
          var n=document.all( objectId).lengt h;
          for(i=0;i<n;++i ) {
          if(document.all (objectId).opti ons[i].selected) {
          document.all(s_ label_name).inn erText =
          document.all(ob jectId).options[i].text;
          }
          }
          }else{
          document.getEle mentById(s_labe l_name).innerHT ML = objectId;
          }
          }
          //-->
          </script>

          </HEAD>
          <BODY>
          <form method="post" action="" id="form_h" name="form_h">
          <table>
          <tr>
          <td width='4%'>
          <tr>
          <td colspan='6'> </td>
          </tr>
          <tr>
          <td>&nbsp;</td>
          <td>
          </td>
          <td>&nbsp;</td>
          <td colspan='1' align='right'>& nbsp;</td>
          <td>
          <input name='cmd_detai l_new' type='button'
          id='cmd_detail_ new' value='ADD DETAIL [CLICK HERE]'
          onclick=detail_ row();>
          </td>
          <td>&nbsp;</td>
          <td colspan='3' align='right'>D ETAIL TOTAL / LOCAL </td>
          <td>
          <input name='two_d_txt _detail_total' type='text'
          id='two_d_txt_d etail_total' value='' size='10'>
          </td>
          <td width='16%'>=EU R</td>
          <td width='30%'>
          <input name='two_d_txt _detail_total_e uro' type='text'
          id='two_d_txt_d etail_total_eur o' value='' size='10'></td>
          </td>
          </tr>
          <tr>
          <td colspan='6'></td>
          </tr>
          </table>
          </td>
          </tr>
          </table>
          <table>
          <tr>
          <td height='20' valign='top'>
          <table width='100%' border='1' cellpadding='0' cellspacing='0'
          valign='top' id='formation'>
          <thead>
          <tr>
          <td width='15%'>&nb sp;<b>GOODS</b></td>
          <td width='5%'>&nbs p;<b>UNIT PRICE</b></td>
          <td width='10%'>&nb sp;<b>CURRENCY</b></td>
          <td width='5%'>&nbs p;<b>QUANTITY</b></td>
          <td width='5%'>&nbs p;<b>TOTAL LINE</b></td>
          <td width='5%'>&nbs p;<b>UPLIFT (%)</b></td>
          <td width='5%'>&nbs p;<b>INCL. UPLIFT</b></td>
          <td width='5%'>&nbs p;<b>=EUR</b></td>
          <td width='5%'>&nbs p;<b>&nbsp;</b></td>
          </tr>
          <thead>
          <tbody>
          <tr>
          <td colspan='10'>
          <label id='label_detai l'>NO RECORDS FOUND</label>
          </td>
          </tr>
          </tbody>
          <input type='hidden' id='two_d_txt_d etail_ids'
          name='two_d_txt _detail_ids' value=''>
          <input type='hidden' id='txt_update_ ids' name='txt_updat e_ids'
          value=''>
          </table>
          </td>
          </tr>
          </table>
          </form>
          </body>
          </html>

          Comment

          • Lasse Reichstein Nielsen

            #6
            Re: calculating in table made by createElement and appendChild

            kiedrea@yahoo.c om (kie) writes:

            [adding DOCTYPE that selects standard mode][color=blue]
            > I have done this, one thing I noticed was that I couldn't control the
            > size of my select boxes:
            >
            > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            > "http://www.w3.org/TR/html4/loose.dtd">[/color]

            ....[color=blue]
            > <SELECT id='test' name='test' style='width:50 '>[/color]

            In CSS, all (non-zero) lengths must have a unit. In this case, I assume
            you mean 50 pixels, so it should be "style='width:5 0px'".

            I quirks mode, browsers allow some errors, and missing units is one of
            them. It is still illegal CSS.
            [color=blue]
            > if I remove the first 2 lines from the code above, the select box will
            > become 50 pixels in width.[/color]

            Yes, because the browser humors you instead of following standards.

            ....[color=blue]
            > I tried adding the line:
            > "sel2.style.wid th ='100';"[/color]

            That is no better. It should still be '100px'.
            [color=blue]
            > Are the style.width used in createElement and the style='width:50 ' in
            > HTML much different commands?[/color]

            No, they are completely equivalent. The elem.style property corresponds
            directly with the style attribute in HTML.

            Still, the browser might be more linient in Javascript than in the
            HTML/CSS parser.

            (That was a lot of code to post!)
            /L
            --
            Lasse Reichstein Nielsen - lrn@hotpop.com
            Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Dom Leonard

              #7
              Re: calculating in table made by createElement and appendChild

              kie wrote:

              <snip>[color=blue]
              >[/color]
              I have tried and[color=blue]
              > failed to extract the row number or "TR" id
              >
              > function calculateAll()
              > {
              > for( var node = this.parentNode ; node; node=node.paren tNode){
              > //if(node.tagName =="TR"){
              > //alert('node name and current row id: ' + node.Name);
              > //alert('node name and current row id: ' +
              > document.forms[0].elements.node. name);
              > //alert('node name and current row id: ' +
              > document.forms[0].elements[node].name);
              > //alert('node name and current row id: ' + node);
              > alert('node name and current row id: ' +
              > document.getEle mentById(node)) ;
              > // }
              > }
              > calculateTab(2, globalClaimLnsR owNum);
              > }
              >
              > I would expect that if "node" is an object, then it should have a
              > name. And I expected that name to be "row_1", "row_2" etc, from the
              > line:
              >
              > "rowSec2.id = 'row_' + globalClaimLnsR owNum;"
              >
              > am I mistaking "node" for an "element"? I have changed the attributes
              > of "TR" elements in the past using lines such as:
              >
              > "document.getEl ementById(tdId) .style.backgrou ndColor = '#000000';"
              >[/color]

              "node" refers to the primary datatype of objects in the DOM which
              support the Node interface, described in W3C DOM recommendations [1]. In
              the above code, the variable named "node" simply means a DOM node
              without regard to whether it is an element or something else (document,
              text node, document fragment or whatever).

              An element is a *node* which supports the Element interface. Elements
              correspond to HTML tags. Under the Element interface the tag name is
              available as node.tagName. Under the node interface of an element, the
              tag name is also availabe as node.nodeName. A subtle difference is that
              node.tagName is undefined on nodes which are *not* elements.

              Name and id are separate attributes of element nodes, so if row number
              information has been placed in the id attribute, id would be used to
              retrieve it as in:

              function getRowNumber(el ement) // for element within row id "row_xxxx"
              {
              for( var node = element.parentN ode; node; node=node.paren tNode)
              { if(node.tagName == "TR")
              return + node.id.substri ng(4);
              }
              }

              [The unary plus operator applied to a string is equivalent to
              parseFloat(stri ng,10)]

              [color=blue]
              > With the "TBODY" element missing, the browser creates it. does that
              > mean before i was unnecesasarily creating a new "TBODY" element each
              > time the user clicks "Add Row"?[/color]
              That is something only you can answer - yes I assumed inserting multiple
              TBODY elements was unnecessary, but didn't look up the HTML DTD either:
              <cite>
              <!ELEMENT TABLE - -
              (CAPTION?, (COL*|COLGROUP* ), THEAD?, TFOOT?, TBODY+)>
              </cite>
              which says one or more TBODY elements are permitted.
              [color=blue]
              > Memory dissipation is also halted by calling a function instead of
              > inserting the code into the elements onchange handler?[/color]
              True to the extent that multiple function objects and closures are not
              created. The main reason for the suggestion, however, was to avoid
              memory leaks in IE6. These are caused by *circular* references between
              document nodes and javascript. The scope chain of a nested function
              (assigned as an event handler) contains the activation object of the
              call to its outer function, so if variables of the outer function refer
              back to the DOM node, the circle is complete.

              For example,

              function detail_row(s_go ods_ ...

              var sel2; ...

              sel2.onchange=f unction(){calcu lateTab(2,globa lClaimLnsRowNum );}

              is prime suspect material.

              An alternative solution to your problem occured to me after the original
              reply. Why not use a static *factory* function to create a handler,
              which can pass a line number and avoid the requirement for an id value
              on the TR. Untested, but along lines of

              function calculateCall( tab_no, line_no)
              {
              return function(){ calculateTab(ta b_no, line_no)}
              }

              and then

              sel2.onchange = calculateCall( 2, globalClaimLnsR owNum);

              on the understanding of that calculateTab would receive
              globalClaimLnsR owNum as at the time calculateCall was called, not as
              updated afterwards.

              This approach will create multiple function objects and closures, but at
              least they are on the smallish side :)
              [color=blue]
              >
              > I need to find out more about nodes,[/color]

              [1].[color=blue]
              >
              > thanks again,[/color]
              You're welcome. As Lasses noted for the style-pixel-width question, the
              amount of code has become excessive for email posting [2]. Providing a
              URL or posting separate cut-down code and code usage questions is the
              way to go.

              <snip>
              [color=blue]
              > var s_browser = "";
              > // W3C & Netscape 6
              > if(document.get ElementById) {
              > s_browser = "netscape6" ;
              > }
              > // browser is IE 4+:
              > else if (document.all) {
              > s_browser = "ie4";
              > }
              > // browser is Netscape 4+:
              > else if (document.layer s) {
              > s_browser = "netscape4" ;
              > }
              > else {
              > s_browser = "";
              > }
              >[/color]

              An observation: page design and code are unlikely to ever work in
              browsers lacking document.getEle mentById support. IIRC, IE4 does not
              support nested functions, and NS4 does not support layers within forms
              (forms within layers are ok).

              <snip>[color=blue]
              > </tbody>
              > <input type='hidden' id='two_d_txt_d etail_ids'
              > name='two_d_txt _detail_ids' value=''>
              > <input type='hidden' id='txt_update_ ids' name='txt_updat e_ids'
              > value=''>
              > </table>[/color]

              INPUT elements are not amongst the permitted child elements of TABLE.
              Basically they go outside all tables or within TD cells.

              Happy testing,
              Dom
              ==============
              [1] W3C
              <URL http://www.w3.org/TR/DOM-Level-2-Core >
              <URL http://www.w3.org/TR/DOM-Level-2-HTML >
              [2] Newgroup FAQ:
              <URL: http://www.jibbering.com/faq/ >

              Comment

              • Dom Leonard

                #8
                Re: calculating in table made by createElement and appendChild

                Lasse Reichstein Nielsen wrote:

                <snip>[color=blue]
                >
                >
                > No, they are completely equivalent. The elem.style property corresponds
                > directly with the style attribute in HTML.
                >
                > Still, the browser might be more linient in Javascript than in the
                > HTML/CSS parser.
                >[/color]

                Mozilla (at least) has an "almost" standards mode [1], triggered by the
                HTML loose DTD, which IIRC permits setting dimensions as pixels by
                default from within javascript as for NS4. Using the strict DTD triggers
                full standards mode and ignores dimensions without unit values.

                Also, thanks for the tip about IE conditional comments [2]. For
                accuracy, the end comment uses the form:
                <![endif]-->
                which certainly wasn't my first guess :)

                cheers,
                Dom

                =======
                [1]





                Comment

                • Dom Leonard

                  #9
                  Re: calculating in table made by createElement and appendChild

                  Forgot the Mozilla URL:
                  [1] http://www.mozilla.org/docs/web-developer/quirks/
                  then[color=blue]
                  > [2]
                  > http://msdn.microsoft.com/library/de...omment_ovw.asp
                  >[/color]



                  Comment

                  • Dr John Stockton

                    #10
                    Re: calculating in table made by createElement and appendChild

                    JRS: In article <7HJ8b.2613$vQ1 .134666@nnrp1.o zemail.com.au>, seen in
                    news:comp.lang. javascript, Dom Leonard <doml.removethi s@senet.andthis .co
                    m.au> posted at Sun, 14 Sep 2003 04:01:55 :-[color=blue]
                    >
                    >[The unary plus operator applied to a string is equivalent to
                    >parseFloat(str ing,10)][/color]

                    It is not equivalent. Consider the string "3k".

                    It is true that, in many cases where a programmer uses parseFloat, unary
                    + would be better. "3l" should generally give an error, not 3.

                    And parseFloat only uses one argument.

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                    Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                    Comment

                    • Lasse Reichstein Nielsen

                      #11
                      Re: calculating in table made by createElement and appendChild

                      Dr John Stockton <spam@merlyn.de mon.co.uk> writes:
                      [color=blue]
                      > JRS: In article <7HJ8b.2613$vQ1 .134666@nnrp1.o zemail.com.au>, seen in
                      > news:comp.lang. javascript, Dom Leonard <doml.removethi s@senet.andthis .co
                      > m.au> posted at Sun, 14 Sep 2003 04:01:55 :-[color=green]
                      > >
                      > >[The unary plus operator applied to a string is equivalent to
                      > >parseFloat(str ing,10)][/color]
                      >
                      > It is not equivalent. Consider the string "3k".[/color]

                      Yes, unary plus is equivalent to the function "Number" (not used as a
                      constructor). The "Number" conversion function works exactly like the
                      automatic type conversions induced by operators, which is what unary
                      plus is (just like Boolean is equivalent to double-negation and the
                      implicit conversion performed by conditionals).

                      I can't really find a reason to use parseInt or parseFloat.

                      /L
                      --
                      Lasse Reichstein Nielsen - lrn@hotpop.com
                      Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
                      'Faith without judgement merely degrades the spirit divine.'

                      Comment

                      • Dom Leonard

                        #12
                        Re: calculating in table made by createElement and appendChild

                        Dom Leonard wrote:
                        [color=blue][color=green]
                        >> function fixFormBug( oForm) // Internet Explorer only[/color]
                        >
                        >
                        > [A cautionary note on this code fix. As written, it patches an IE form
                        > object after elements have been added, but makes no repairs if field
                        > elements have been removed. In this particular case that should be not
                        > be a problem, but would test submission]
                        >[/color]

                        This has gone further. Testing shows what looks like two closely related
                        problems when inserting form field elements using DOM methods under IE:

                        Problem 1
                        ==========

                        Form field elements given a "name" attribute alone (without an "id"),
                        are not made named properties of the FORM object when a field is
                        inserted into the document using appendChild().

                        The lack of the FORM property does not seem to upset form submission,
                        just programatic access to the fields. This problem occurs outside
                        tables so does not appear to be related to table usage in test code.

                        Providing an "id" attribute with the same value as the "name" attribute
                        of field elements appears to fix the problem, and is the work around I
                        would now suggest. It will not work, of course, for multiple field
                        elements, such as radio inputs, sharing the same name.

                        Problem 2
                        ==========

                        Only the first radio inputs added to a FORM using appendChild() can be
                        navigated to using the keyboard. Any additional (radio) inputs can not
                        be set by clicking. Basically no radio group is created, and setting a
                        FORM property to an array of radio inputs sharing the same name fails to
                        improve the situation.

                        The only work around I could devise for this was to create radio inputs
                        by inserting HTML code into the innerHTML property of an outer element.

                        ===========

                        Because of these findings, as well as the lack of handling for form
                        field deletes, I can only describe the fixFormBug() function as
                        intermediate test code. Kie, I would suggest monitoring this thread to
                        see if better solutions are proposed, but if not to remove the
                        fixFormBug code and supply id as well as name values for the form field
                        elements.

                        best regards,
                        Dom

                        ====== cut down test code =======

                        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html4/loose.dtd">
                        <html>
                        <head>
                        <title>IE6 DHTML Form Element test</title>

                        <script type="text/javascript">

                        var rowCount=0;

                        function addRow( form)
                        {
                        var tbody = document.getEle mentById("table Body");
                        var tr = document.create Element("TR");
                        var td = document.create Element("TD");
                        var oText;
                        var oRadio;
                        var radioInnerHTML = "";
                        var oSel, oOpt;
                        var useInnerHTML = form.useInnerHT ML.checked;
                        var includeId = form.includeId. checked;

                        oText = document.create Element("INPUT" );
                        oText.type="tex t";
                        oText.name="tex t" + rowCount;
                        if(includeId)
                        oText.id = "text" + rowCount; // same as name
                        oText.value=row Count;

                        if(useInnerHTML )
                        { radioInnerHTML =
                        '<input type="radio" name="radioGrou p" '
                        + ' id="radio' + rowCount + '"'
                        + ' value="radio' + rowCount + '"'
                        + (rowCount ? "" : " checked")
                        + ">";
                        }
                        else
                        { oRadio = document.create Element("INPUT" );
                        oRadio.name="ra dioGroup";
                        oRadio.type="ra dio";
                        oRadio.id = "radio" + rowCount;
                        oRadio.value = oRadio.id; // always set radio id
                        if(rowCount==0)
                        { oRadio.defaultC hecked = true; // ??
                        oRadio.checked = true;
                        }
                        else
                        oRadio.checked = false;
                        oRadio.disabled =false;
                        }

                        oSel = document.create Element("SELECT ");
                        oSel.name = "sel" + rowCount;
                        if(includeId)
                        oSel.id = "sel" + rowCount;
                        oOpt = document.create Element("OPTION ");
                        oOpt.innerHTML = "option1";
                        oOpt.value="opt 1";
                        oSel.appendChil d(oOpt);
                        oOpt = document.create Element("OPTION ");
                        oOpt.innerHTML = "option2";
                        oOpt.value = "opt2";
                        oSel.appendChil d(oOpt);

                        tbody.appendChi ld(tr);
                        tr.appendChild( td);
                        if(useInnerHTML )
                        td.innerHTML = radioInnerHTML;
                        else
                        td.appendChild( oRadio);
                        td.appendChild( oText);
                        td.appendChild( oSel);
                        alert("td.inner HTML: " + td.innerHTML);

                        ++rowCount;
                        }
                        function checkForm( form)
                        {
                        var oEls = form.elements;
                        var el;
                        var msg;
                        for( var i = 0; i < oEls.length; ++i)
                        {
                        el = oEls[i];
                        if(el.tagName == "OPTION")
                        continue; // ignore for now
                        if(el.className == "test")
                        continue; // part of test chrome
                        if(el.id && !form[el.id])
                        alert("element with id " + el.id + " not in FORM");
                        if(el.name && !form[el.name])
                        { msg = "element with name " + el.name + " not in FORM";
                        if(el.name && !oEls[el.name])
                        msg+="\nit is not a named property of the elements array
                        either";
                        if(el.id && form[el.id])
                        msg+="\nit IS in the FORM under it's id of " + el.id;
                        alert(msg);
                        }
                        if(!(el.name || el.id))
                        alert( el.tagName + " [type=" + el.type + "] "
                        + "value: " + el.value + "without name or id encountered");
                        }
                        }

                        function makeFieldUnionB yName(oEls, name)
                        {
                        var result = null;
                        var resultArray = false;
                        for( var i = 0; i < oEls.length; ++i)
                        {
                        if( oEls[i].name!=name)
                        continue;
                        if( result && !resultArray)
                        { result = [result];
                        resultArray = true;
                        }
                        if(resultArray)
                        result[result.length]=oEls[i];
                        else
                        result=oEls[i];
                        }
                        return result;
                        }
                        function fixFormBug( oForm) // Internet Explorer only
                        {
                        var oEls = oForm.elements;
                        var name;
                        for( var i = 0; i < oEls.length; ++i)
                        {
                        name = oEls[i].name;
                        if(name && !oForm[ name])
                        oForm[name] = makeFieldUnionB yName(oEls,name );
                        }
                        }
                        </script>
                        </head>
                        <body>
                        <p>Reload the page if changing check box values.
                        </p>
                        <p>Clicking "check Form" should produce no alerts. Mozilla and Opera pass.
                        </p>
                        <p>Clicking "test Form Fix" before "check Form" suppresses alerts in IE
                        but doesn't fix radio group behavior.
                        </p>
                        <hr>
                        <form name="testForm" action="test.ht ml">

                        <!-- form field used as test controls have class "test" -->

                        <input type="checkbox" name="includeId " class="test">
                        include id attribute on text/select INPUT elements<br>
                        <input type="checkbox" name="useInnerH TML" class="test">
                        use innerHTML for radio inputs<br>

                        <button type="button" onclick="addRow (this.form)" class="test">ad d
                        row</button>
                        <button type="button" onclick="checkF orm(this.form)" class="test">ch eck
                        Form</button>
                        <button type="button" onclick="fixFor mBug(this.form) " class="test">te st
                        form fix</button>
                        <input type="submit" value="submit" class="test">
                        <table>
                        <tbody id="tableBody" >

                        <tbody>
                        </table>

                        </form>

                        </body>
                        </html>



                        Comment

                        • kie

                          #13
                          Re: calculating in table made by createElement and appendChild

                          thanks Lasse,

                          an add on of 'px' makes all the difference! something simple that i
                          haven't been practicing, but will from now on. including the use of:
                          [color=blue]
                          > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                          > "http://www.w3.org/TR/html4/loose.dtd">[/color]

                          at the top of all my HTML. do you and other developers you know use
                          'loose' or 'strict' as a rule of thumb?

                          with browsers allowing users such as myself to get away with emitting
                          cetain code, bad habits can be made. i wonder, does 'relaxed' coding
                          slow the browser down? or just make the page incompatible with less
                          tolerant browsers?

                          thanks for the tips,

                          kie

                          Comment

                          • Lasse Reichstein Nielsen

                            #14
                            Re: calculating in table made by createElement and appendChild

                            kiedrea@yahoo.c om (kie) writes:
                            [color=blue]
                            > at the top of all my HTML. do you and other developers you know use
                            > 'loose' or 'strict' as a rule of thumb?[/color]

                            I am not sure I would consider myself a "developer" with the (low)
                            number of pages I have made. But I do use "strict" whenever possible.
                            [color=blue]
                            > with browsers allowing users such as myself to get away with emitting
                            > cetain code, bad habits can be made. i wonder, does 'relaxed' coding
                            > slow the browser down? or just make the page incompatible with less
                            > tolerant browsers?[/color]

                            I doubt it is slower. Most browsers are very tolerant of user mistakes
                            (they have to be with the amount of crap HTML out there), so that is
                            probably not a problem either (i.e., I don't know of a less tolerant
                            browser that doesn't understand HTML 4).

                            I always use the optional end tags, always quote attribute values, and
                            try to go strict by the standards, even where browsers don't require it.
                            That is just how I am. :) I follow standards very strictly because I
                            believe it to make code that is less error prone and more maintainable
                            in the long run.

                            /L
                            --
                            Lasse Reichstein Nielsen - lrn@hotpop.com
                            Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
                            'Faith without judgement merely degrades the spirit divine.'

                            Comment

                            • Dr John Stockton

                              #15
                              Re: calculating in table made by createElement and appendChild

                              JRS: In article <llsr72y1.fsf@h otpop.com>, seen in
                              news:comp.lang. javascript, Lasse Reichstein Nielsen <lrn@hotpop.com >
                              posted at Sun, 14 Sep 2003 18:24:54 :-[color=blue]
                              >Dr John Stockton <spam@merlyn.de mon.co.uk> writes:
                              >[color=green]
                              >> JRS: In article <7HJ8b.2613$vQ1 .134666@nnrp1.o zemail.com.au>, seen in
                              >> news:comp.lang. javascript, Dom Leonard <doml.removethi s@senet.andthis .co
                              >> m.au> posted at Sun, 14 Sep 2003 04:01:55 :-[color=darkred]
                              >> >
                              >> >[The unary plus operator applied to a string is equivalent to
                              >> >parseFloat(str ing,10)][/color]
                              >>
                              >> It is not equivalent. Consider the string "3k".[/color]
                              >
                              >Yes, unary plus is equivalent to the function "Number" (not used as a
                              >constructor) . The "Number" conversion function works exactly like the
                              >automatic type conversions induced by operators, which is what unary
                              >plus is (just like Boolean is equivalent to double-negation and the
                              >implicit conversion performed by conditionals).
                              >
                              >I can't really find a reason to use parseInt or parseFloat.[/color]

                              Use parseInt for bases other than 10 (not needed for 0x<hex>).
                              Use parseInt to truncate a decimal part.

                              Use either if the string may contain non-whitespace to be ignored after
                              the numeric part.

                              Unary +, being stricter in what it accepts, is safer.
                              Math.floor(+val ue) is only a little longer than parseInt(value) .

                              --
                              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                              <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
                              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
                              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.

                              Comment

                              Working...