Error trying to overlay and remove elements with removeChild - javascript

i have a problem in the following code snippet.
for (var i=0;i<data.parlist.length;i++){
var inp = document.createElement("input")
var label = document.createElement("label")
var labelValue = document.createElement("label")
var subDiv = document.createElement("div")
var br = document.createElement("br")
try{
var dBtn = document.getElementById(data.parlist[i].id);
var dLabel = document.getElementById(data.parlist[i].id + " label")
var dDiv = document.getElementById(data.parlist[i].id +" div");
var inprad = document.getElementById(data.parlist[i].id+" inp_rad");
var dLabelRad = document.getElementById(data.parlist[i].id + " label_rad")
var dSubDiv = document.getElementById(data.parlist[i].id +" div_rad");
dSubDiv.replaceChild(inprad);
dSubDiv.removeChild(dLabelRad);
dDiv.removeChild(dSubDiv);
dDiv.removeChild(dBtn);
dDiv.removeChild(dLabel);
myDiv.removeChild(dDiv);
}catch{
console.log("no")
}
This for loop is inside a function that when clicking on a button of a station shows the parameters.in this way:
What you see in the images works, but the problem that I have come to try to clarify is that when I press the button for example as station 1 appears in the image and then I press the button for example of station 2 the try that is supposed to you must remove the previous parameters with removeChild does not work, the parameters of station 1 remain in the div and the parameters of station 2 are added below these instead of being removed
Within the try there is a problem but I do not know what it is, I say this because when I check the page and open the console I get the message that I left in the catch a "no"
Thanks for reading my problem and any suggestions are welcome as I am desperate to find a solution.

You need to pass 2 inputs to the replaceChild function.
parentNode.replaceChild(newChild, oldChild);
For more info refer Mozilla docs here.
Here is some additional advice
When you log for debugging, use some meaningful messages. In your case you could do
try {
...
} catch (err) {
console.log(err);
}
From the questions nothing is clear about what is there in data.parlist and whether that is implemented properly.

Related

onClick Add to Grid from an Array but duplicates on second iteration

Use case is to create Add/show/select/delete text messages on a page. I have used array to store the messages on each click till here it works fine but when I try to create Divs and show the messages in grid, I am having duplication on each click. I can see that my function is reading the array fine and creating the div's on the first click but it does not clear the previously created div on second iteration. Not sure how to approach this. Please advise.
here is the snippet.
<script>
//<!-- Fetch data from Textarea when user Click Save and create or push in an array -->
let ArrNotes = [];
function SaveNote() {
let edittext = document.getElementById("editor").value;
ArrNotes.push(edittext);
document.getElementById("SavedNote").innerHTML = ArrNotes;
let container = document.getElementById("GridNotes");
container.className= "GridNotes";
ArrNotes.forEach(createGrid);
function createGrid(item,index)
{
text = undefined;
var tag = document.createElement("div");
tag.className= "grid";
var text = document.createTextNode(index + ": " + item);
//tag.appendChild(text);
container.appendChild(text);
}
}

How can i append a child to a div that has a random number as an id?

READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);

Javascript word count price calculator

Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone

Dynamicaly creating and removing a div

I have been strugling with this for a while and I am sure there is a simple answer to this. What happens is I remove a div called "payment" then dynamicaly create it again so I can add to it. That then gets repeated as the infomation that needs to be added to it changes.
I have mangaged to get this so far.
function clearPage()
{
var d = document.getElementById("contain");
var d_nested = document.getElementById("payment");
var deleteNode = d.removeChild(d_nested);
}
function createPayment()
{
payment = document.createElement("div");
payment.id = "mine";
document.getElementById("contain").appendChild(payment);
}
function printOnPage()
{
var x = names.length;
for( var i = 0 ; i < x ; i++ )
{
var para = document.createElement("p");
var paymentDiv = document.getElementById("payment");
paymentDiv.appendChild(para);
var txtName = document.createTextNode("Item: ");
para.appendChild(txtName);
var txtNameArray = document.createTextNode(names[i]);
para.appendChild(txtNameArray);
var txtQty = document.createTextNode(" Qty: ");
para.appendChild(txtQty);
var txtQtyArray = document.createTextNode(qty[i]);
para.appendChild(txtQtyArray);
var txtCost = document.createTextNode(" Cost: ");
para.appendChild(txtCost);
var txtCostArray = document.createTextNode(prices[i]);
para.appendChild(txtCostArray);
}
}
Related HTML
<div id="contain">
<p>Payment</p>
<div id="payment">
<br />
</div>
</div>
It needs the ID of payment for both my CSS rules and for my creating the text that goes in it.
This is the error I get in FireFox
Error: paymentDiv is null Source File:
http://itsuite.it.brighton.ac.uk/ks339/sem2/javascript/js.js Line: 76
Hope someone can provide some insight in to this and please tell me if I am completly off!
Thanks
Edit: Is it easior to clear the div rather than delete it, how would I go about doing such a thing?
In create_payment(), you set the ID to 'mine'. Shouldn't it be 'payment'?
I do not understand your requirements very well, but anyway you cannot create multiple items in the page using the same id attribute, if you want to duplicate an item and still have control over it, you should be using class instead.
Try switching your code into jquery it will be cleaner and easier to understand for you & me.
Your problem is the fact that in createPayment() you're setting the id to 'mine':
payment.id = "mine";
while later on in printOnPage() you're looking for the element using id 'payment':
var paymentDiv = document.getElementById("payment");
As you mention in your edit, it is far easier just to clear the div than to remove it, specially if you still need it later.
To clear a DIV-block just set it's content to empty:
document.getElementById('payment').innerHTML = "";
I hope you find a solution! Good luck!

Event handler causes many alerts

I am working on a Phonegap app, in which I access device's contacts. I then store upto 10 contacts in window.localStorage. To do so, when the user select a button, I create a div which has three elements.
An image (contact icon that represents male/female contact)
The name of the contact
Another image (represents 'add' sign to add it to window.localStorage)
I then associate an event handler, which will first check if the contact already exists in the localStorage and then proceed to add the contact. Here is the code
function checkDuplicate(somevalue)
{
for(var i=0;i<10;i++) {
if(window.localStorage.getItem(i)!=null) {
if(window.localStorage.getItem(i)==somevalue) {
navigator.notification.alert('Entry exists at Button:'+i);
return false;
}
}
}
//chosenButton is a global variable
window.localStorage.setItem(chosenButton,somevalue);
document.getElementById('contactNumberField').textContent=somevalue;
}
//Problem is with the event listener attached to span2. Please read below
function addContact(item)
{
var parentDiv = document.getElementById('thelist');
var childDiv = document.createElement('li');
var span1 = document.createElement('span');
span1.style.float='left';
span1.innerHTML = "<img src='keypad-contact.png'/>";
var span2 = document.createElement('span');
span2.style.float='right';
span2.innerHTML="<img src='keypad-addcontact.png'/>";
span2.addEventListener('click',function({checkDuplicate(item.number);},false);
childDiv.textContent=item.name;
childDiv.style.color='white';
childDiv.appendChild(span1);
childDiv.appendChild(span2);
parentDiv.appendChild(childDiv);
}
function onSuccess(contacts)
{
var objArray = new Array();
for(var i=0; i<contacts.length;i++) {
var tempObj = new Object();
tempObj['name']=contacts[i].displayName;
tempObj['number']=contacts[i].phoneNumbers[0].value;
objArray.push(tempObj);
}
objArray.sort(
function(a,b){
var nameA = a.name.toLowerCase(),nameB=b.name.toLowerCase();
if(nameA < nameB) return -1;
else if(nameA > nameB) return 1;
return 0;
});
for(var i=0; i<objArray.length;i++) addContact(objArray[i]);
}
function onDeviceReady()
{
var options = new ContactFindOptions();
options.multiple=true;
var field = ["displayName","phoneNumbers"];
navigator.contacts.find(field, onSuccess, function(){alert('NA');}, options);
}
Problem
When I try to add a contact which is already present in window.localStorage, for my first touch on span2, I get one alert. If I try to add again by touching it for the second time, I get two alerts.. and this goes on. The trouble is with the event handler associated with span2. However, I don't know how to over come this situation. How can I ensure that irrespective of how many times I press span2, I get alert only once. How to remove the event handler as soon as it is fired?
Please help.
Fixed:
The issue was not with adding event handlers dynamically. I happen to use iScroll (cubiq) for my project and that caused the trouble. Now I am not receiving multiple alerts. The trick is to declare the globlal scroller variable only once.
var scroller = null;
and then in the function
if(!scroller) scroller = new iScroll('scrollableDiv');
I hope this could be a useful tip for people who are using iScroll and struggling with multiple alerts like me.

Categories