Remove child not working - javascript

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);
// …
}

Related

i want to make my shoppingcart local so every time i refresh the page my stuff still needs to be in there but i just dont find the right way to do it

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.

Other js function is ignoring my realtime calc function

I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.

Upload small image in a dynamic form?

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!

SharePoint 2016 - JSLink - save not working with IE but working with Chrome

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.

Check Users Permissions on Facebook

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);
});

Categories

Resources