Javascript: Adding and removing elements to dom - javascript

I am trying to dynamically add new elements to my html. But i am currently stuck on the "second level". It starts with a single div where new elements will get stored at:
<div id="inputquestions"></div>
When I click a button, new elements will get added to the div via a javascript function which looks something like this
function addQuestion() {
var div = document.createElement('div');
questionID++; // increment questionID to get a unique ID for the new element
div.className = 'newQuestion';
div.id = 'newQuestionID';
div.innerHTML =
"<div class='input-group'>" +
"<input id='question-" + questionID + "' class='form-control' name='questionbox' type='text' placeholder='New Question'/>" +
"<button class='btn btn-secondary' onclick='removeQuestion(this.parentNode)' type='button'>Remove</button>" +
"</div>" +
"<div class='btn-group' role='group' aria-label='Basic example'>" +
"<button class='btn btn-secondary' onclick='addRadioButton()' type='button'>+ Radiobutton</button>" +
"</div>";
document.getElementById('inputquestions').appendChild(div);
}
This will create multiple divs inside the first div and I now want each div to create new divs for them individually but can't figure out how to do it. How does my function addRadioButton() have to look like in order to make the new divs appear inside the div I pressed the button at?

In your function addRadioButton() you can look at event.target.parentElement to get the <div> that contains the <button> that was clicked on.
Then you add the new elements into that <div>.

Related

Bootstrap container closes early

I'm trying to use bootstrap containers to make rows of 3 panels; however, with my current code one panel ends up in the container and two are left outside.
I'm not too sure where I'm going wrong.
I've counted and recounted my <div> and </div> so many times so I don't believe that is the issue
//var count = 0; above
//for loop for n > 3 above
html = "";
if (count%3===0) {
html = html + "<div class=\"container\">" +
"<div class=\"row\">";
}
html = html + "<div class=\"col-sm-4\">" +
"<div class=\"panel panel-primary\">" +
"<div class=\"panel-heading\">" + name + "</div>" +
"<div class=\"panel-body\"><img src=\"" + imageURL + "\"class=\"img-responsive\" style=\"width:100%\" alt=\"Image\"> </div>" +
"<div class=\"panel-footer\"> <h2>$" +
price.toString() + recString + "</h2>" + description + "</div> </div> </div>";
if (count%3===2) {
html = html + "</div> </div> <br> <br>"
}
count = count + 1;
$('#items').append(html);
Here is the items div in my html file.
<div id="items" >
</div><br>
By appending to the $items div in each iteration of the loop, the web browser checks and sees that the items div has been closed after the append. When a parent is closed, the web browser closes all the children, including the container and row divs.
Solution was to append at the end outside of the loop

Javascript onclick change content of HTML

I am adding new div when user clicks the blue button but everytime user click button, content of whole html is getting dissappeared i need a solution for it.
Also, is it possible to add an animation to it?
here is the demo just press blue button, type something and hit blue button again.
https://jsfiddle.net/61tbq4q6/2/
This is html part:
<input type="button" id="ebookParts" value="" class="custBut">
<div id="myContainerDiv">
</div>
This is the JS:
var i = 1;
$( "#ebookParts" ).click(function() {
var container = document.getElementById("myContainerDiv");
var html = document.getElementById('myContainerDiv').innerHTML;
html = html + "<div class=\"col-sm-12\">"
+ "<div class=\"form-group\">"
+ "<div class=\"col-sm-6\"><label>Name</label><input class=\"form-control\" type=\"text\" name=\"display_name[]\"></div>"
+ "<div class=\"col-sm-2\"><label>Part</label><input class=\"form-control\" type=\"text\" name=\"part[]\" value=" + i + "></div>"
+ "<div class=\"col-sm-2\"><label>Pages between</label><input class=\"form-control\" type=\"text\" name=\"pages[]\"></div>"
+ "<div class=\"col-sm-2\"><label>price</label><input class=\"form-control\" type=\"text\" name=\"price[]\"></div>"
+ "</div>"
+ "</div>";
container.innerHTML= html;
i++;
return false;
});
If you're saying the problem is that whatever the user manually typed into an input is disappearing, it's because you're destroying those inputs and replacing them with new ones when you do container.innerHTML = html. Your original assignment to var html = ... only captures actual attributes, not JS properties.
What you need to do if you're going to append new DOM elements using HTML, while keeping the old content, is to use .insertAdjacentHTML instead of .innerHTML.
This way, instead of taking the existing DOM, converting it to HTML markup, adding more HTML to it, and replacing the old DOM elements with new ones generated from the HTML, you'll be simply creating the new ones from the HTML and adding them where you want them.
var i = 1;
$( "#ebookParts" ).click(function() {
var container = document.getElementById("myContainerDiv");
var html = "<div class=\"col-sm-12\">"
+ "<div class=\"form-group\">"
+ "<div class=\"col-sm-6\"><label>Name</label><input class=\"form-control\" type=\"text\" name=\"display_name[]\"></div>"
+ "<div class=\"col-sm-2\"><label>Part</label><input class=\"form-control\" type=\"text\" name=\"part[]\" value=" + i + "></div>"
+ "<div class=\"col-sm-2\"><label>Pages between</label><input class=\"form-control\" type=\"text\" name=\"pages[]\"></div>"
+ "<div class=\"col-sm-2\"><label>price</label><input class=\"form-control\" type=\"text\" name=\"price[]\"></div>"
+ "</div>"
+ "</div>";
// The "beforeend" parameter inserts the new content inside the
// container after the existing content.
container.insertAdjacentHTML("beforeend", html);
i++;
return false;
});
It's because you getting html, than changing it an then inserting again in your page. When you copying your html, you don't copying values, which already passed in inputs. Instead of this you need to use .appendChild() method, and you will also need document.createElement()
If you need only to add the div one time. Then check with a "if" before add the div.
var isAdded=false;
$( "#ebookParts" ).click(function() {
if(!isAdded){
//your code
}
});

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?
function newBox
{
numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
var pizzaBoxCode = "<div class = 'PizzaBox'>"
+ " <h6>Box number " + numOfBoxes + "</h6>"
+ " <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
+ " <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
+ "</div>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
PizzaBoxHolder.innerHTML += pizzaBoxCode;
}
Any help is appreciated. Thanks!
The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.
var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder");
PizzaBoxHolder.appendChild(pizza);
Working fiddle.

How to Replace Element In Variable Using jquery And Get Result In Another Variable

I am having a variable with HTML content. Similar to "objHtml" variable below.
I want to replace a div tag with Id = 123 with another new div tag.
var objHtml = "<div> " +
"<div id='123' class='class1'>Text1</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
// I want to construct this new object using "objHtml", and want to replace div having id = 123 with div having id = 125.
// This Html is in the object and not visible or render on the page.
var newObjHtml = "<div> " +
"<div id='125' class='class1'>Text5</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
Can any one answer how to replace an element in variable with another element?
$(document).ready(function() {
var objHtml = "<div> " +
"<div id='123' class='class1'>Text1</div>" +
"<div id='124' class='class1'>Text2</div>" +
"</div>";
//Create temporary element
var elem = $(objHtml);
//Find the element and replace it with new HTML
elem.find('#123').replaceWith("<div id='125' class='class1'>Text5</div>");
//Read outerHTML property and update your variable or create new variable
objHtml = elem.prop("outerHTML");
alert(objHtml)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Delete corresponding table row with unique button id

My end goal here is to take a button with a unique id from the index. Based off of the id is clicked (i.e. Which button I click) it deletes that corresponding table row. For example if I hit a delete button with an id of 1..then I want to delete the 1st table row within that table. I am having trouble understanding how I would do this.
Here is my code.
count = ["<TR>", "<TR>", "<TR>", "<TR>"]
$.each(count, function(index,value) {
index++;
$("#deletingRows table").append("<tr><td class='deleteRow' style='font-weight: bold;'>" + 'Row Number: ' + "<input type='text' name='rowNumber' id='rowNumber' style='margin-left: 45px;' value=" + index + ">" + "</input>" + "<input type='button' id='" + index + ' + "name='delete' value='Delete This Row'></input>" + "</td></tr>");
});
You can simplify this to :-
Give class delete to your button.
$('.delete').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
or just use the name itself.
$('input[name=delete]').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
See .closest()
Remember to put the click handler under document.ready.

Categories

Resources