So I want to create a function that will let me add/remove an element in the HTML, I’m already done with the “add” part that increments the id value onchange (example: id=tag1, id=tag2, etc). My problem is on the “remove” part, I don’t know how to put an incremental value inside onclick=remove_tag(). Here’s my code
function update() { var selObj = document.getElementById("skill_tags"); var selVal = selObj.options[selObj.selectedIndex].text; let counter = 0; document.getElementById("textarea").innerHTML += "<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal + "<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag('tag"+ counter +"');></button></span></li></div>"; $("#textarea div").each(function(i){this.id = "tag" + (i + 1)}) } function remove_tag(id) { document.getElementById(id).innerHTML = ""; }
What I want to do is to make my onclick on the button to be (onclick=”remove_tag1″, onclick=”remove_tag2″, onclick=”remove_tag3″, etc). Sorry for the question, still a newbie in JavaScript. Thanks for the help. Here’s an image https://pasteboard.co/k7hb7cVHSQHj.png
<div class="resume-skill-item"> <h5> <ul class="list-inline"> <div align="right"> <select id="skill_tags" onchange="update()"> <option selected="true" disabled="disabled">*Select All That Applies</option> <option value="mechanic">Mechanic</option> <option value="appliance_repairer">Appliance Repairer</option> <option value="carpenter">Carpenter</option> <option value="plumber">Plumber</option> <option value="technician">Technician</option> </select> </div> </ul> <div id="textarea" class="large-single-textarea"> </div> </h5> </div> ```
Advertisement
Answer
You can use data attribute on delete button to keep reference on added items when you want to delete them.
function update(e) { var selObj = document.getElementById("skill_tags"); var selVal = selObj.options[selObj.selectedIndex].text; let counter = 0; document.getElementById("textarea").innerHTML += `<div class="tags_inline" id="${e.value}"><li class="list-inline-item"><span class="badge badge-dark">"${selVal}"<button data-select-id="${e.value}" class="fa fa-times-circle text-white" id="delete" onclick=remove_tag(this) >remove</button></span></li></div>`; } function remove_tag(e) { document.getElementById(e.dataset["selectId"]).remove(); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="resume-skill-item"> <h5> <ul class="list-inline"> <div align="right"> <select id="skill_tags" onchange="update(this)"> <option selected="true" disabled="disabled">*Select All That Applies</option> <option value="mechanic">Mechanic</option> <option value="appliance_repairer">Appliance Repairer</option> <option value="carpenter">Carpenter</option> <option value="plumber">Plumber</option> <option value="technician">Technician</option> </select> </div> </ul> <div id="textarea" class="large-single-textarea"> </div> </h5> </div>