Dynamic HTML using Javascript

I use javascript to dynamically assemble a grid of input elements in HTML. Each line has 4 input elements, and the user can add or delete lines as needed. Every time they add or delete a row, I dynamically restore the grid.

My problem is that after I create the grid for the second time, I cannot refer to any of the elements. I believe that the DOM now has 2 inputs of each element with the same name and is confused when I try to reference by name.

My question is: is there any way to reset the listing of DOM element names, so is the name "resued" still unique in every dynamic assembly?

+3
source share
2 answers

You can provide node with the identifier of another unique prefix every time you create a grid, and enable it every time you refer to node by id.

Or you can change your code so as not to rebuild the entire grid every time.

However, I think it may be that you have identified the problem incorrectly or I do not understand your question correctly. If you do not want to remove the old table element from the document before inserting a new one, there should be no conflict over identifiers or names.

+2
source

Each line has 4 input elements and the user can add or delete lines as they are necessary. Each time they add or remove row, I rebuild the grid dynamically.

? DOM . .

html , / :

<html>
<head>

<style>
<!--
a,input{
    margin: .2em;
}
-->
</style>

<script type="text/javascript"
    src="http://api.prototypejs.org/javascripts/prototype.js"></script>

<script type="text/javascript">

function createGrid(id){
    addRow($(id),0);
}

function deleteRow(elem, index){
    elem.children[index].remove();
}

function addRow(elem, index){
    var row = new Element('div',{'class':'row'});
    for(var i = 0; i < 4; i++){
        row.insert({
            bottom: new Element('input',{'type':'text'})
        });
    }
    row.insert({
        bottom: new Element('a',{'href':'#'})
            .update('Add Row')
            .observe('click',function(event){
                var row = Event.element(event).up();
                var addIndex = $A(row.up().children).indexOf(row);
                addRow(elem, addIndex);
                Event.stop(event);
        })
    }).insert({
        bottom: new Element('a',{'href':'#'})
            .update('Delete Row')
            .observe('click',function(event){
                var row = Event.element(event).up();
                var delIndex = $A(row.up().children).indexOf(row);
                deleteRow(elem, delIndex);
                Event.stop(event);
        })
    });
    if(index > 0){
        elem.children[index-1].insert({after:row});
    }else{
        elem.insert({top:row});
    }
}

Event.observe(window,"load",function(){
    createGrid('grid');
});
</script> 

</head>
<body>

<div id="grid">
</div>

</body>
</html>

/ . , lib, .

0

Source: https://habr.com/ru/post/1756956/


All Articles