Friday, September 25, 2009

Dynamic rows in Javascript

Create a demo.html with this code and try to see the functionality

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function addRow(div,value,x){

    var ni = document.getElementById(div);
    var numi = document.getElementById(value);
    var num = (document.getElementById(value).value -1)+ 2;
    numi.value = num;
   
    var divIdName = "my"+num+x+"Div";
    var newdiv = document.createElement(div);
    newdiv.setAttribute("id",divIdName);
    newdiv.innerHTML = "<table width=\'100%\' class=\'listTable\' >"
                        +"<tr class=\'listTR"+(num%2)+"\' onMouseOver=this.style.backgroundColor=\'DEDEBE\' onMouseOut=this.style.backgroundColor=\'\'>"
                        +"<td><input type='text' name='studNo'/></td>"
                        +"<td><input type='text' name='studName'/></td>"
                        +"<td><a href=\"javascript:;\" class=\"menu\" onclick=\"removeEvent(\'"+divIdName+"\',\'"+div+"\')\">Remove</a></td>"
                        +"</tr></table>";
    ni.appendChild(newdiv);
}
function removeEvent(divNum,div){
    var d = document.getElementById(div);
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
}
</script>
</head>
<body>
<form action="">
    <table>
    <tr bgcolor="#737328"><td>
        <table>
        <tr><td>Student No</td><td>Student Name</td><td>Actions</td></tr>
        <tr><td><input type="text" name="studNo"/></td><td><input type="text" name="studName"/></td><td> </td></tr>
        </table>
        </td></tr>
        <tr bgcolor="#737328"><td>
            <input type="hidden" name="theValue" id="theValue" value="0"/>
        <div id="myDiv"></div>
        </td></tr>
        <tr>
        <td><p><a href="javascript:;" onclick="addRow('myDiv','theValue','');"><strong>Add More</strong></a></p></td>
        </tr>
    </table>
</form>
</body>
</html>

No comments:

Post a Comment

Please comment on this