I have JS code which creates paragraph and input elements according to html. But I need this code to create each element only once.
Peace of Javascript code
function comFunction(sel) {
switch (sel.value) {
case 'skype':
var skype = document.createElement("P");
var temp = document.createTextNode("Enter your skype");
var input = document.createElement("input");
input.type = "text";
skype.appendChild(temp);
form.appendChild(skype);
form.appendChild(input);
break;
}
HTML code
<form id="form">
<select name="liason" id="liason" onchange="comFunction(this);">
<option value="skype">Skype</option>
<option value="icq">ICQ</option>
<option value="facebook">Facebook</option>
<option value="email">e-mail</option>
</select>
</form>
If you add an id to the elements being created and appended to the DOM, you can then check for their existence before running the code that would create them a second time:
function comFunction(sel) {
switch (sel.value) {
case 'skype':
if(document.getElementById("skypeParagraph") === null) {
var skype = document.createElement("P");
skype.setAttribute("id", "skypeParagraph");
var temp = document.createTextNode("Enter your skype");
var input = document.createElement("input");
input.type = "text";
skype.appendChild(temp);
form.appendChild(skype);
form.appendChild(input);
}
break;
}
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.