0

I am doing an e commerce project, and for the shipping part, I let the user enter one area place asssociated with a price and then these two values are displayed with a remove button. The user can generate multiple times of these three elements.(and at each of these three generated elements, there are two input hidden to handle the values and then process that data with php) When clicked on the remove button, i would like to remove the entered area+the price+the remove button by their similar class name. But how to do that when it is dynamically generated ? This is the HTML part:

        <label for="places">Places/area : </label>
        <input type="text" name="ps_places" id="ps_places" value="" >
        <label for="ps_price" "> Price : </label><input type="text" name="ps_price" id="ps_price" value="" >
        <button type="button" onclick="ps_add()">OK</button>
        <div id="display1"></div>

And the javascript part:

function addElement(parentId, elementTag, elementId, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('class', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}


function ps_add() 
{

var pv = document.getElementById('ps_places').value;
var prv = document.getElementById('ps_price').value;

if((pv != "") && (prv != ""))
{
ps_id++;

addElement("display1", "span", ps_id, "- ");
addElement("display1", "label", ps_id, pv);
addElement("display1", "span", ps_id, " :  ");
addElement("display1", "label", ps_id, prv);
addElement("display1", "span", ps_id, "    ");
addElement("display1", "button", ps_id, "Remove");
addElement("display1", "br", ps_id, "");

var input1 = document.createElement("input");
input1.setAttribute("type", "hidden");
input1.setAttribute("class", "ps_id");
input1.setAttribute("name", "ps_places[]");
input1.setAttribute("value", pv);
display1.appendChild(input1);

var input2 = document.createElement("input");
input2.setAttribute("type", "hidden");
input2.setAttribute("class", "ps_id");
input2.setAttribute("name", "ps_price[]");
input2.setAttribute("value", prv);
display1.appendChild(input2);
}
document.getElementById('ps_places').value= ""; 
document.getElementById('ps_price').value= "";  
}
user2305415
  • 172
  • 1
  • 3
  • 18

1 Answers1

3

As you have added , I would assume you use jQuery. You can remove all the elements by their classname using this:

$(".classname").remove();

If it was by mistake, and if you need a pure JavaScript solution, you can use this:

elems = document.querySelectorAll(".classname");
for (var elem in elems)
  elems[elem].parentNode.removeChild(elems[elem]);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252