Search code examples
javascriptarraysstruts

add to array with javascript in struts


OK I have this in a jsp page

<div id="productList">  
  <logic:iterate id="product" indexId="aid" name="TeamMaintenanceForm" property="team.productList">                             
          <div id='<bean:write name="product" property="id" />' >
                <bean:write name="product" property="name" /> 
          </div>        
        </logic:iterate>                                
</div>  

Now I would like to add an object to this array with javascript something like

  function addProduct(){
       var object;
       object.name='newProduct';
       object.id=5;
       productList.add(newProduct);
}

SO that the new object shows up with the others in the array and so that when i do submit this page it gets submited to the form with the objects in the array.

Is there an easy way to do this?


Solution

  •   function addProduct(){
        var object;
        object.name='newProduct';
        object.id=5;
    
        // get the reference of div (productList)
        var productList = document.getElementById('productList')  ;
    
        // create the div structure of children
        var newProductDiv = "<div id='"+object.id +"' />'"+object.name + "</div>"; 
    
        // append the children to the productList div.
        productList.appendChild(newProductDiv);
     }
    

    you can make it parameterized

    function addProduct(object){
    
        // get the reference of div (productList)
        var productList = document.getElementById('productList')  ;
    
        // create the div structure of children
        var newProductDiv = "<div id='"+object.id +"' />'"+object.name + "</div>"; 
    
        // append the children to the productList div.
        productList.appendChild(newProductDiv);
    }