Dynamicaly creating and removing a div - javascript

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!

Related

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

variable is null when pulling from a div

Sorry in advance for the extremely banal question, I'm positive I am missing something extremely simple. Without further adieu;
I'm getting a type error when I try to pull a block of text, and a button, from a div in my HTML. The div has an id that I am accurately referencing. For oversight, I am attempting to retrieve the text, apply coloring to each word (cycling through red, blue, and green), and replace the original text with my colored text. It works fine in JSFiddle, but I cannot get the data to retrieve in espresso - transcribeText is null.
var transcribeText = document.getElementById("divideTranscript");
transcribeText.onclick = function() {
var words = document.getElementById("transcriptText");
var textArray = words.innerHTML.split(" ");
var count = 0;
var colorArr = ["red", "blue", "green"];
var newWords = document.createElement("div");
for(var i = 0; i < textArray.length; i++){
var item = textArray[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.className = colorArr[count % 3];
newSpan.id = "word"+i;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
count++;
};
words.parentNode.replaceChild(newWords, words);
}
<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button"> Transform the
Transcript! </div>
Your problem is that the javascript runs before the HTML exists, therefore, you cannot get any ids. There are several ways around this. First is my favorite:
window.onload = function name() {
//code to be excuted
}
The function will be called after HTML has loaded. body.onload = function name() also works.
The second method (no pun intended haha) is to put the script tag at the end of the body tag.
<body>
<script></script>
</body>
Personally, I use the first one more commonly because I have a template I religiously use, and I don't like moving tags around. That's just me, whatever works for you! Hope this Helps!

What's wrong with this JavaScript code? I'm trying to change the text of <h1> element on click

I just started learning JavaScript.
I'm trying to change the text on a click.What's wrong with this code.
Please let me know.
Thanks
<!DOCTYPE html>
<html>
<body>
<script>
function change_text(id)
{
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
var x = Document.getElementById("heading");
for(var i=0;i<arr.length;i++)
x.innerHTML=arr[i];
x.style.visibility="hidden";
}
</script>
<h1 onclick="change_text()" id="heading">Click on this text!</h1>
</body>
</html>
For one thing, you have two quotes here:
""oops! Once more!"
should be:
"oops! Once more!"
Document needs to be all lower-case (document).
change_text(id) is never used, and
x.style.visibility="hidden" needs to be moved outside the for loop.
You don't need a for loop at all, though, you just need to increment i++ every time the method is called, otherwise it will skip straight to "Goodbye".
<script>
var i = 0;
function change_text()
{
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
var x = document.getElementById("heading");
i++;
x.innerHTML=arr[i];
if(i >= arr.length) {
x.style.visibility="hidden";
}
}
</script>
EDIT:
EDIT2: OK, you got the idea before!
instead of "heading"
var x = Document.getElementById("heading");
you need to put the passed in value, id.
var x = Document.getElementById(id);
before this, you never actually use that id.
Also remember to pass that id in,
h1 onclick="change_text('heading')"
Change this line;
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
and this line
var x = Document.getElementById("heading");
to this;
var arr = new Array('Now Click Again','oops! Once more!','I\'m Leaving!','Good Bye!');
var x = document.getElementById(id);
First, i don't know if it is a typo in your question but you have one extra " in your string array, this is how it should look.
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
And I don't know what you are trying to do with your for loop but the text you are showing will always be the last one in your array. Could you clarify what your are trying to achieve with the text in the h1 element?
Last of all, if you hide your element clearly your text won't show up, you should remove this line unless there is something I didn't understand correctly :
x.style.visibility="hidden";
Oh, and I think that your script element should have a type="text/javascript"
<script type="text/javascript">...
Unrelated to the question but if you can't spot the strings mistake in your array maybe you should change IDE. Even Notepad++ colors the strings, it might have helped you figure this one out.

jQuery .before() then find it's content and apply the for loop. What am I doing wrong

I need to dynamically add a couple of things like container then find it in DOM and fill with a list of numbers. Here is the way I do it but I feel like it is redundant and maybe I should do it another way. The only issue is that I have to do it all with javascript and cant hard code any container. That is why first I add it and then try to find it.
JS Bin working example http://jsbin.com/okikohu/1/
The code:
<script>
$(function(){
var obj = $('form'),
total = 6;
obj.before('<div class="container"/>');
var container = $('body').find('.container');
for (var i = 0, limit = total; i < limit; i++) {
container.append('-<span class="step" id="is'+(i+1)+'">'+(i+1)+'</span>-');
}
});
</script>
<form>some form</form>
obj.before('<div class="container"/>');
var container = $('body').find('.container');
Instead of using before() and then a DOM query, you could create the element with the jQuery(html) constructor and simply insertBefore() it somewhere while still holding the reference:
var total = 6,
container = $('<div class="container"/>').insertBefore('form');

Accessing textarea value inside td on iframe

I'm freaking out with an issue I cannot solve.
I don't have so much experience with iFrames and jQuery but it's needed to solve this asap because it's a big problem in an app.
I've an iFrame with a div and some rows. I've a textarea and a button whos calling a javascript method who's recovering the value inserted in textarea
But it's not working, either of options I tried have worked.
This is the code, could you help me?
Thank you!
http://pastebin.com/xsWzG2VH
EDIT:
I'm trying to recover the value of TEXTOAYUNTAMIENTO, a textarea inside td structure with that function.
When I press the button to recover it, all of them are empty or null.
This is the method:
function checkayuntamiento(value)
{
alert(value);
alert('Hola');
alert($('#TEXTOAYUNTAMIENTO', window.parent.document).html());
alert('<%=indice%>');
alert('<%=TEXTOAYUNTAMIENTO%>');
alert('<%=DESCMODOENVIO%>');
var valor = document.getElementById("TEXTOAYUNTAMIENTO");
var valor5 = document.getElementsByName('TEXTOAYUNTAMIENTO')[0].value
var valor2 = document.getElementById("TEXTOAYUNTAMIENTO").innerHTML;
//var elem = $('#salida_'+id);
var idi = $("#TEXTOAYUNTAMIENTO").val();
var asdf = $(this).closest('tr').next().find(".AYUNTAMIENTOS").val();
var valor3 = document.getElementById("PRUEBA");
var valor4 = document.getElementById("PRUEBA").innerHTML;
//var elem = $('#salida_'+id);
var idi2 = $("#PRUEBA").val();
var asdf2 = $(this).closest('td').next().find(".PRUEBA").val();
alert(asdf);
alert(idi);
alert(valor);
alert(valor2);
alert(asdf2);
alert(idi2);
alert(valor3);
alert(valor4);
alert(valor5);
}

Categories