简体   繁体   中英

Add remove html element using javascript

I want to create a form to add multiple images with caption . As I m php and mysql person. So if i could get new fields on clicking addmore then i can do the rest php mysql part. How can i set var x to create a new row to provide new browse button and caption textfield.

<script type="text/javascript">
<!--
function addMore() {
if (document.getElementById && document.createElement) {
    var x = ;
    document.getElementById('inserthere').appendChild(x);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}

function delMore() {
if (document.getElementById && document.createElement) {
    var node = document.getElementById('inserthere')
    node.removeChild(node.childNodes[0]);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}
// -->
</script>

</head>

<body>
<table>
<tr><td>Select Image<input type="file" name="img[]" id="img"  /></td><td>Add caption
<input type="text" name="img_cap[]" id="img_cap" /></td>
</tr>
<span id="inserthere"></span>
</table>

<a href="javascript:addMore()" class="page">add More</a><br />
<a href="javascript:delMore()" class="page">remove</a>

</body>

Till someone replies i am going to learn , explore internet and try try try.....

It's not the prettiest way but the simplest, quickest way is probably to give the table an id property (say, for example, 'imgtable' ), and do the following in your addMore() function:

var x = document.createElement('tr'); // create a new row ready to add
x.innerHTML = '<td>Select Image<input type="file" name="img[]" id="img"  /></td><td>Add caption <input type="text" name="img_cap[]" id="img_cap" /></td>'; // fill it with your code
document.getElementById('imgtable').appendChild(x) // add the new row to the table

As you want to learn more though, be sure to look up methods like document.createDocumentFragment() as a way of appending individually declared elements to an object before you actually add it to the DOM. The innerHTML method I have used can be quicker but it's not as neat and can be more difficult to debug than declaring a document fragment.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM