I have this function which uses innerHTML
to insert html
into a div
:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
var uniqueID = ""
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var length = 7
for (var i = length; i > 0; --i) uniqueID = chars[Math.floor(Math.random() * chars.length)];
uniqueID = uniqueID
introNewSection.innerHTML = '<div id=' uniqueID '><div > <div style="margin-top: -20px;"> <h6 >Intro <a href="#" onclick="javascript:deleteInput(' uniqueID ')" style="text-align: right; float: right; margin-right: 12px;"><i style="color: gray;"></i></a></h6> <p >Section 1</p> <div > <div > <textarea type="text" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea> </div> </div> </div> </div></div>'
submitbutton.style.display = ''
}
and then my html
:
<div id="intro-row"></div>
however, as you can see in the introNewSection.innerHTML
, I have a <textarea type="text" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea>
the problem is, this function displayInputIntro()
can be triggered multiple times. Every time its triggered, and there's any text inside the textarea, it just clears it and I don't know why. how can I fix this?
CodePudding user response:
First thing you need to close the HTML tags properly, is not closing properly , i see is not having closing tag while assigning html to innerHTML, Second thing whenever you are using innerHTML it will override the html content. If you want to inject the html then use insertAdjacentHTML tag and execute as below
introNewSection.insertAdjacentHTML('afterend', 'additional HTML code');
Note: You should find out why the function is triggering multiple times.