Using either Javascript or HTML, I have a dynamic form that refreshes/updates each time the user adds data to the table. It even has a 'modify' button and an 'erase' button to delete that particular line. However, one last thing I want to add is a button that would allow the user to upload a picture that would fit in the very last slot of the column. How do I achieve it in such a way that every time the user 'adds' the data (and another row is formed) with that particular image, the next time he wants to add another row he is able to select another image?
window.onload = load;
var id = 1;
var colEmpleados = [];
var colSectores = [{id:1, nombre:"Sector 1"},
{id:2, nombre:"Sector 2"},
{id:3, nombre:"Sector 3"}];
function load()
{
var btnAgregar = document.getElementById("btnAgregar");
btnAgregar.onclick = agregar;
var btnConfirmar = document.getElementById("btnConfirmar");
btnConfirmar.onclick = confirmarModificacion;
var btnCancelar = document.getElementById("btnCancelar");
btnCancelar.onclick = cancelar;
cargarSelectSectores();
habilitarIngreso();
}
function habilitarIngreso()
{
var rowA = document.getElementById("rowAgregar");
rowA.style.display = 'block';
var rowM = document.getElementById("rowModificar");
rowM.style.display = 'none';
}
function habilitarModificar()
{
var rowM = document.getElementById("rowModificar");
rowM.style.display = 'block';
var rowA = document.getElementById("rowAgregar");
rowA.style.display = 'none';
}
function confirmarModificacion()
{
var idEmpleado = document.getElementById("idEmpleado").value;
for(var i = 0; i<colEmpleados.length;i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
colEmpleados[i].nombre = document.getElementById("txtNombre").value;
colEmpleados[i].apellido = document.getElementById("txtApellido").value;
colEmpleados[i].sector = document.getElementById("sltSector").value;
colEmpleados[i].edad = document.getElementById("txtEdad").value;
colEmpleados[i].ingreso = document.getElementById("dtpIngreso").value;
}
}
mostrar();
habilitarIngreso();
limpiarForm();
}
function cancelar()
{
habilitarIngreso();
limpiarForm();
}
function borrar()
{
var idEmpleado = this.getAttribute("idEmpleado");
for(var i=0; i<colEmpleados.length; i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
colEmpleados.splice(i,1);
}
}
mostrar();
}
function modificar()
{
habilitarModificar();
var idEmpleado = this.getAttribute("idEmpleado");
for(var i=0; i<colEmpleados.length; i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
document.getElementById("idEmpleado").value = colEmpleados[i].idEmpleado;
document.getElementById("txtNombre").value = colEmpleados[i].nombre;
document.getElementById("txtApellido").value = colEmpleados[i].apellido;
document.getElementById("sltSector").value = colEmpleados[i].sector;
document.getElementById("txtEdad").value= colEmpleados[i].edad;
document.getElementById("dtpIngreso").value= colEmpleados[i].ingreso;
}
}
mostrar();
}
function cargarSelectSectores()
{
var selectSectores = document.getElementById("sltSector");
selectSectores.innerHTML = "<option id='0'>--- Sectores ---</option>";
for(var i = 0; i<colSectores.length; i++)
{
selectSectores.innerHTML +="<option id="+colSectores[i].id+">"+colSectores[i].nombre+"</option>";
}
mostrar();
}
function agregar()
{
var nombre = document.getElementById("txtNombre").value;
var apellido = document.getElementById("txtApellido").value;
var sector = document.getElementById("sltSector").value;
var edad = document.getElementById("txtEdad").value;
var fechaIngreso = document.getElementById("dtpIngreso").value;
var empleado = {};
empleado.idEmpleado = id;
empleado.nombre = nombre;
empleado.apellido = apellido;
empleado.sector = sector;
empleado.edad = edad;
empleado.ingreso = fechaIngreso;
colEmpleados.push(empleado);
id++;
limpiarForm();
mostrar();
}
function limpiarForm()
{
var colInputs = document.getElementsByTagName("input");
for(var i = 0; i<colInputs.length; i++)
{
if(colInputs[i].type != "button")
{
colInputs[i].value = "";
}
}
document.getElementById("sltSector").value = "0";
}
function mostrar()
{
var bodyTabla = document.getElementById("datosEmpleados");
bodyTabla.innerHTML = "";
for(var i = 0; i<colEmpleados.length; i++)
{
var emp = colEmpleados[i];
bodyTabla.innerHTML +="<tr><td>"+emp.idEmpleado+"</td><td>"+emp.nombre+"</td><td>"+emp.apellido+"</td><td>"+emp.edad+"</td><td>"+emp.sector+"</td><td>"+emp.ingreso+"</td><td><input class='btnBorrar' type='button' value='Borrar' idEmpleado="+emp.idEmpleado+" /></td><td><input class='btnModificar' type='button' value='Modificar' idEmpleado="+emp.idEmpleado+" /></td></tr>";
}
var colBotones = document.getElementsByClassName("btnBorrar");
for(var i = 0; i<colBotones.length; i++)
{
colBotones[i].onclick = borrar;
}
var colBotonesModificar = document.getElementsByClassName("btnModificar");
for(var i = 0; i<colBotonesModificar.length; i++)
{
colBotonesModificar[i].onclick = modificar;
}
}
Thanks in advance!
Related
This is my code but I don't know where to start to add localstorage.
I am really trying every website for help because I just can't find it.
var _currentArr;
var _ItemsInCart = [];
var _totalPayment = 0;
function getArticle(item, addDetails) {
var article = document.createElement("article");
var h3 = document.createElement("H3");
h3.appendChild(document.createTextNode(item.title));
article.appendChild(h3);
var figure = document.createElement("FIGURE");
var img = document.createElement('img');
img.src = 'images/'+item.img;
var figcaption = document.createElement('figcaption');
figcaption.textContent = 'Meal by: '+item.cook;
figure.appendChild(img);
figure.appendChild(figcaption);
article.appendChild(figure);
// if need details
if (addDetails) {
var dl = document.createElement("dl");
var dt1 = document.createElement("dt");
var dd1 = document.createElement("dd");
dt1.textContent = 'calories:';
dd1.textContent = item.calories;
dl.appendChild(dt1);
dl.appendChild(dd1);
var dt2 = document.createElement("dt");
var dd2 = document.createElement("dd");
dt2.textContent = 'servings:';
dd2.textContent = item.servings;
dl.appendChild(dt2);
dl.appendChild(dd2);
var dt3 = document.createElement("dt");
var dd3 = document.createElement("dd");
dt3.textContent = 'days to book in advance:';
dd3.textContent = item.book;
dl.appendChild(dt3);
dl.appendChild(dd3);
var dt4 = document.createElement("dt");
var dd4 = document.createElement("dd");
dt4.textContent = 'type:';
dd4.textContent = item.type;
dl.appendChild(dt4);
dl.appendChild(dd4);
article.appendChild(dl);
}
// info div
var div = document.createElement("DIV");
div.setAttribute("class", "info");
var p = document.createElement("P");
p.textContent = '€'+item.price+'/pp';
var a = document.createElement("A");
a.setAttribute("href", '#');
a.textContent = 'order';
a.setAttribute("id", item.id);
if (addDetails) {
a.setAttribute("data-item", JSON.stringify(item));
a.className = "order placeOrderInCart";
} else {
a.className = "order orderBtn";
}
// in div
div.appendChild(p);
div.appendChild(a);
article.appendChild(div);
return article;
}
function makeTemplateFromArray(arr) {
_currentArr = [];
_currentArr = arr;
var container = document.getElementById('dynamicContent');
container.innerHTML = '';
if (arr && arr.length) {
arr.forEach(function (item, index) {
// append article
container.appendChild(getArticle(item, false));
});
}
}
function makeTemplateFromItem(item) {
if (item) {
var container = document.getElementById('popupContentWrapper');
container.innerHTML = '';
container.appendChild(getArticle(item, true));
}
}
function showModal(id) {
// find item by id
if (_MEALS && id) {
var found = _MEALS.find(function(item) {
if (item.id === parseInt(id)) {
return true;
}
});
if (found) {
makeTemplateFromItem(found);
}
}
// open modal
document.getElementById('popup').style.display = "block";
}
// sorting
function sortItems() {
var a = _MEALS.slice(0, _MEALS.length);
var k = event.target.value;
makeTemplateFromArray(doSortData(k, a));
}
function doSortData(key, arr) {
var compare = function ( a, b) {
if ( a[key] < b[key] ){
return -1;
}
if ( a[key] > b[key] ){
return 1;
}
return 0;
};
return arr.sort( compare );
}
// change direction
function changeDirection() {
var val = event.target.value;
var a = _currentArr.slice(0, _currentArr.length);
if (val === 'desc') {
makeTemplateFromArray(a.reverse());
} else {
makeTemplateFromArray(_MEALS);
}
}
// search on input
function searchInArray() {
var val = event.target.value;
if (val && val.length > 1) {
val = val.toLowerCase();
var arr = _MEALS.filter(function (item) {
if (item.title.toLowerCase().includes(val)) {
return true;
}
});
makeTemplateFromArray(arr);
} else {
makeTemplateFromArray(_MEALS);
}
}
// prepare options
function prepareOptions(obj) {
var select = document.getElementById('sortby');
Object.keys(obj).forEach(function (key) {
var opt = document.createElement('option');
opt.value = key;
opt.innerHTML = key;
select.appendChild(opt);
});
}
// add item in cart
function addItemInCart(item) {
_ItemsInCart.push(item);
var elem = document.getElementById('cartCounter');
elem.innerHTML = _ItemsInCart.length;
}
// show cart
function showCart() {
// prepare template
var container = document.getElementById('cartItems');
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tfoot = document.createElement("tfoot");
container.innerHTML = '';
var thBody = '<tr><th>Meal</th><th>Price</th></tr>';
thead.innerHTML = thBody;
// tbody
_totalPayment = 0;
_ItemsInCart.forEach(function(item) {
_totalPayment += parseInt(item.price);
var tBodyTemp = '<tr><td>'+item.title+'</td><td>€ '+item.price+'</td></tr>';
tbody.innerHTML += tBodyTemp;
});
// tfoot
var tfootBody = '<tr><td>Total</td><td>€ '+_totalPayment+'</td></tr>';
tfoot.innerHTML = tfootBody;
table.appendChild(thead);
table.appendChild(tbody);
table.appendChild(tfoot);
container.appendChild(table);
// open modal
document.getElementById('cart').style.display = "block";
}
// proceed to checkout
function proceedToCheckout() {
document.getElementById('cartoverview').classList.add('hidden');
document.getElementById('personalinformation').classList.remove('hidden');
}
// validate form submit
function validatepersonalInfoForm() {
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.remove('hidden');
// set values
var val = document.querySelector('input[name="paymentmethod"]:checked').value;
document.getElementById('price').innerHTML = '€ '+_totalPayment;
document.getElementById('paymentmethod').innerHTML = 'in '+val;
}
function setRandomItem() {
var max = _MEALS.length;
var min = 0;
var number = Math.floor(Math.random() * (max - min + 1)) + min;
var item = _MEALS[number];
document.getElementById('mealofthedayimg').src = 'images/'+item.img;
}
// listen on click event for order button
document.body.addEventListener("click", function (event) {
// close modal box
if (event.target.classList.contains("close")) {
document.getElementById('cart').removeAttribute('style');
document.getElementById('popup').removeAttribute('style');
// remove classes from element
document.getElementById('cartoverview').classList.remove('hidden');
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.add('hidden');
}
// open modal box
if (event.target.classList.contains("orderBtn")) {
event.preventDefault();
showModal(event.target.getAttribute("id"));
}
// add item in cart
if (event.target.classList.contains("placeOrderInCart")) {
event.preventDefault();
var item = JSON.parse(event.target.getAttribute("data-item"));
if (item) {
addItemInCart(item);
}
}
});
setTimeout( function() {
// console.log(_MEALS);
makeTemplateFromArray(_MEALS);
prepareOptions(_MEALS[0]);
setRandomItem();
}, 100);
After you add something into _ItemsInCart, set _ItemsInCart as data in localstorage.
Before you want to get something from _ItemsInCart, get data from localstorage first and set it to _ItemsInCart.
_ItemsInCart should always sync with your data in localstorage.
How to use localstorage:
https://www.w3schools.com/html/html5_webstorage.asp
Advice: If possible, separate your DOM manipulating code with your logic code.
I've got a strange behaviour with a JSLINK I'm using on my SP. The save button of the form is not working with IE if I change the value of the field that the JSLINK is transforming but it's ok with Chrome.
The field is type of Multiline plain text. I'm using using to save some JSON.
Here is the code:
(function() {
var loaded = false;
var repeaterFormArr = [
"<input type='text' id='nameInput' placeholder='Nom complet' class='ms-long ms-spellcheck-true intervenantsBox' required>",
"<input type='text' id='addressInput' placeholder='Adresse' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='phoneInput' placeholder='Telephone' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='emailInput' placeholder='Email' pattern=\"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$\" title='xxx#yyy.zzz' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<select name='typeActor' id='typeActor' class='ms-long intervenantsBox'><option value='plaignant'>Plaignant</option><option value='avocat'>Avocat</option><option value='DPO'>DPO</option><option value='demandeur'>Demandeur</option></select>",
];
var ControlRenderModeIntervenant;
var repeaterFormValues = [];
function includeCss() {
if (loaded) return;
loaded = true;
var link = document.createElement('link');
link.href = _spPageContextInfo.siteAbsoluteUrl + '/Style%20Library/CSS/intervenantsEditCustom.css';
link.rel = 'stylesheet';
document.head.appendChild(link);
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledViewTemplate(ctx) {
ControlRenderModeIntervenant = ctx.ControlMode;
if (ctx.CurrentItem[ctx.CurrentFieldSchema.Name] && ctx.CurrentItem[ctx.CurrentFieldSchema.Name] != '[]') {
var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name].replace(/"/g, "\"").replace(/(<([^>]+)>)/g, "");
repeaterFormValues = JSON.parse(fieldValue);
}
return GetRenderHtmlRepeaterValuesIntervenants();
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledEditFTemplate(ctx) {
var field = ctx.CurrentFieldSchema,
encodedName = field.Name + '_' + field.Id + '_$NumberField';
ControlRenderModeIntervenant = ctx.ControlMode;
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
if (formCtx.fieldValue) {
repeaterFormValues = JSON.parse(formCtx.fieldValue);
}
// Register a callback just before submit.
ctx.FormContext.registerGetValueCallback(field.Name, function() {
return JSON.stringify(repeaterFormValues);
});
ctx.FormContext.registerInitCallback(field.Name, function() {
document.getElementById('innerFormIntervenants').addEventListener('submit', function(evt) {
evt.preventDefault();
AddIntervenant();
return false;
});
var deleteLinks = document.getElementsByClassName('delete-link');
if (deleteLinks.length > 0) {
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener("onclick", function(evt) {
evt.preventDefault();
DeleteItem(deleteLinks[i].getAttribute('data-myAttri'));
return false;
});
}
}
});
// formCtx.registerGetValueCallback(formCtx.fieldName, function() {
// return JSON.stringify(repeaterFormValues);
// });
var HTMLViewTemplate = "<form id='innerFormIntervenants'>{Controls}<div><input type='submit' value='Add' style='margin-left:0'></div><br/><div id='divRepeaterValues'>{RepeaterValues}</div><br/></form>";
var returnHTML = "";
for (index = 0; index < repeaterFormArr.length; ++index) {
returnHTML += repeaterFormArr[index];
}
returnHTML = HTMLViewTemplate.replace(/{Controls}/g, returnHTML);
returnHTML = returnHTML.replace(/{RepeaterValues}/g, GetRenderHtmlRepeaterValuesIntervenants());
return returnHTML;
}
function GetRenderHtmlRepeaterValuesIntervenants() {
var index;
var innerindex;
var HTMLItemsTemplate = "<table width='600px' style='border:1px solid #ababab;'>{Items}</table>";
var HTMLItemTemplate = "<tr>{Item}</tr>";
var HTMLValueTemplate = "<td>{Value}</td>";
if (ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.EditForm || ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.NewForm) {
HTMLItemTemplate = "<tr>{Item}<td><a class='delete-link' data-myAttri='{Index}' href='#'><img src='/SiteAssets/IMG/user-delete.png' class='deleteUserButton'/></a></td></tr>";
}
var returnHTML = "";
var tempValueHtml;
for (index = 0; index < repeaterFormValues.length; ++index) {
tempValueHtml = "";
for (innerindex = 0; innerindex < repeaterFormValues[index]["Intervenant"].length; ++innerindex) {
tempValueHtml += HTMLValueTemplate.replace(/{Value}/g, repeaterFormValues[index]["Intervenant"][innerindex]["Value"]);
}
returnHTML += HTMLItemTemplate.replace(/{Item}/g, tempValueHtml);
returnHTML = returnHTML.replace(/{Index}/g, index);
}
if (repeaterFormValues.length) {
returnHTML = HTMLItemsTemplate.replace(/{Items}/g, returnHTML);
}
return returnHTML;
}
function AddIntervenant() {
var innerFormIntervenants = document.getElementById('innerFormIntervenants');
if (innerFormIntervenants.checkValidity()) {
var index;
var tempRepeaterValue = [];
for (index = 0; index < innerFormIntervenants.length; index++) {
if (innerFormIntervenants[index].type != "submit" && innerFormIntervenants[index].type != "button" && innerFormIntervenants[index].type != "reset") {
tempRepeaterValue.push({
"ID": innerFormIntervenants[index].id,
"Value": innerFormIntervenants[index].value
});
innerFormIntervenants[index].value = "";
}
}
repeaterFormValues.push({ "Intervenant": tempRepeaterValue });
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
}
function DeleteItem(index) {
repeaterFormValues.splice(index, 1);
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.OnPreRender = includeCss;
overrideCtx.Templates.Fields = {
myCustomField: {
View: IntervenantsRepeaterFiledViewTemplate,
DisplayForm: IntervenantsRepeaterFiledViewTemplate,
NewForm: IntervenantsRepeaterFiledEditFTemplate,
EditForm: IntervenantsRepeaterFiledEditFTemplate
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
In Debug, I can see that the callback function is called. Then it goes inside the JS of SharePoint for saving the item. But the save button is just going to grey and then nothing append.
I try to check if the user has accepted a list of permissions. I have this:
window.FB.api("me/permissions", function (resp) {
var IsValid = true;
var perm = "public_profile";
var PermsArray = resp.data;
var PermsNeeded = perm.split(",");
var Unit = PermsNeeded.length;
for (var I = 0; I < Unit; I++) {
var Per = PermsNeeded[I];
if (PermsArray[Per] == null) {
IsValid = false;
break;
}
}
callBack(IsValid);
});
When i try this, after i accepted the public_profile permission, i get IsValid = false.
Whats wrong? :s
UPDATE:
This works:
window.FB.api("me/permissions", function (resp) {
var IsValid = false;
var perm = "public_profile";
var PermsArray = resp.data;
var PermsNeeded = perm.split(",");
var Unit = PermsNeeded.length;
var UnitAccepted = PermsArray.length;
for (var I = 0; I < Unit; I++) {
var Per = PermsNeeded[I];
for (var J = 0; J < UnitAccepted; J++) {
var AccPer = PermsArray[J];
if (AccPer.permission == Per) {
IsValid = true;
break;
} else {
IsValid = false;
}
}
}
callBack(IsValid);
});
I want to make it like for example when the word spilt into elements, the checking part will not restrict to only four.(In code comment it as "this part"). I want to be depending on how many the elements split so that it will be correct.
if(original[0]==$("#box1").text()&&original[1]==$("#box2").text()&&original[2]==$("#box3").text()&&original[3]==$("#box4").text())
This only restricted to four, then the checking will be correct. How can I do it such as there will be three split elements or more then four elements and the checking will still be correct.
<script>
js_var = "<?php echo $output ?>";
var c = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'];
var div_id = ['id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'];
var box_id = ['box1','box2','box3','box4','box5','box6','box7','box8','box9','box10'];
var original = js_var.split("#");
var balls90= js_var.split("#");
var x = document.getElementById("demo");
for (var i=0; i < original.length; i++) {
var el = document.createElement('div');
el.id = c[i];
el.innerHTML = original[i];
x.appendChild(el);
}
function getNumbers() {
var player1 = new Array();
balls90.sort(function() {
return Math.random() - .25;
document.getElementById("shuffle").onclick = function(){displayDate()};
});
for (var i = 0; i < balls90.length; i++) {
document.writeln('<div id='+box_id[i]+' class=box droppable=true ondrop=drop(event)
ondragover=allowDrop(event)></div>');
}
for (var i = 0; i < balls90.length; i++) {
player1.push(balls90[i]);
document.writeln('<div id='+div_id[i]+' draggable=true droppable=true
ondragstart=drag(event)>'+balls90[i]+'</div>');
}
}
getNumbers();
function dragWord(dragEvent){
dragEvent.dataTransfer.setData("text/html",
dragEvent.target.textContent+"|"+dragEvent.target.parentNode.id);
}
function dropWord(dropEvent){
var dropData = dropEvent.dataTransfer.getData("text/html");
var dropItems = dropData.split("|");
var prevElem = document.getElementById(dropItems[1]);
prevElem.getElementsByTagName("div")[0].textContent = dropEvent.target.textContent;
dropEvent.target.textContent = dropItems[0];
dropEvent.preventDefault();
}
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
//this part
if(original[0]==$("#box1").text()&&original[1]==$("#box2").text()&&original[2]==$("#box3").text()&&original[3]==$("#box4").text())
{
alert('correct');
}
}
<script>
Something along these lines:
var result = true;
for (var i=0, i<original.length, ++i) {
if (original[i] !== $("#box"+(i+1)).text()) {
result = false;
break;
}
}
if(result) {
alert('correct');
}
Hai
I am doing a web page. In that there is a drop down contains some products, when we select an item it will display below with a remove button as dynamically. My problem is that al the products removed correctly but a product that has product id 5 is not removed? What's the problem? Below is my code
<script type="text/javascript>
function validate(frm_name){
var hiddenFeild = document.getElementById('product');
var addedItems = hiddenFeild.value;
var brokenItems = addedItems.split(",");
if(isEmpty(hiddenFeild.value)){
alert("No Product Added.");
return false;
}
if(brokenItems.length < 3){
alert("Please Add One More Product.");
return false;
}
return true;
}
function removeme(id){
compareDiv = document.getElementById('compare_product');
var remDiv = document.getElementById(id);
compareDiv.removeChild(remDiv);
var hiddenFeild = document.getElementById('product');
var addedItems = hiddenFeild.value;
var brokenItems = addedItems.split(",");
hiddenFeild.value = '';
for(var i = 0 ; i < brokenItems.length-1; i++){
if(brokenItems[i] != id){
hiddenFeild.value = hiddenFeild.value +brokenItems[i]+',';
}
}
}
function selectProduct(){
var flag = 0;
compareDiv = document.getElementById('compare_product');
var proValue = document.getElementById('frm_product').value;
if(proValue != 0){
var product = proValue.split("productvalue");
var productid = product[0];
var productname = product[1];
var hiddenFeild = document.getElementById('product');
var addedItems = hiddenFeild.value;
var brokenItems = addedItems.split(",");
for(var i = 0 ; i < brokenItems.length; i++){
if(brokenItems[i] == productid){
flag = 1;
alert('Already Added');
}
}
if(flag == 0){
hiddenFeild.value = hiddenFeild.value +productid+',';
compareDiv.innerHTML = compareDiv.innerHTML + '<div id="'+productid+'" style="height:30px;"><div style="float:left;" id="added_product">'+productname+'</div><div style="float:right;"><input onClick="removeme('+productid+');" id="remove" name="remove" type="button" value="remove" /></div></div>';
}
}
}
</script>
In general removeChild has to be called from the parent node of the node that should be removed. So try this:
function removeme(id) {
var remDiv = document.getElementById(id);
remDiv.parentNode.removeChild(remDiv);
// …
}