Javascript onclick change content of HTML - javascript

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

Related

textarea clears when using innerhtml [duplicate]

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.
If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.
if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
var _row = "<tr id='queue_row_" + items_in_queue + "'>";
_row += "<td>";
_row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
_row += "</td>";
_row += "<td>";
_row += _item;
_row += "</td>";
_row += "</tr>";
document.getElementById("upload_queue").innerHTML += _row;
document.getElementById("upload_image_" + items_in_queue).style.display = "none";
items_in_queue++;
document.getElementById("uploader_holder").innerHTML +=
'<input id="upload_image_' + items_in_queue +
'" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' +
'onchange="add_to_upload_queue()" style="display: inline;" />';
}
Yeah... you're going to want to use appendChild instead of modifying the inner HTML:
var myInput = document.createElement("INPUT");
// do stuff to my input
var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);
That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

Javascript: Adding and removing elements to dom

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>.

how to put a button inside div where data is filled dynamically through $.each function

This should be very simple but i am struggling here.
I have a parent div which have multiple child div. These child div are generated according to $.each() function. Number of times function run, num of div get generated.Now, i want to write a server side function on button click but i am unable to list that button in these child div.
<div class="div1">
<div class="div2">
// this is the button which i cant see in my div2 div
<button type="input">follow</button>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/Home/GetUsers", null, function(data) {
$(".div1").html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>"
html += "</div>";
$(".div1").append(html);
});
});
});
</script>
</div>
</div>
Any type of guidance appreciated.
If you'd like to add a button per child div you can do it in this way:
$(document).ready(function() {
var parent = $(".div1");
$.getJSON("/Home/GetUsers", null, function(data) {
parent.html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
html += "<button type='button' class='newButton'>Click Me!</button>";
html += "</div>";
parent.append(html);
});
});
// In order to ensure that the button click is handled no matter when it was
// added, we can delegate the handler to the parent.
parent.on('click', '.newButton', function(e) {
var button = $(this);
// Handle the individual button click server side call here.
});
});

Counting the number of appended elements for form submission

I have a web page that is a dynamic form. It allows users to specify any number of Attributes to devices. These attributes can be select option lists. When the user selects this, they are presented with a button to add options.
My problem is that I need to know how many options there are for each attribute. I have tried using var counter=$('.class-name').next().val(); to try and count them alert(counter); to see if it works. But all I get is an alert of undefined so the var counter is not being initalised.
I need to know the number of options for each select list to be able to group them together and know which options go with a particular attribute. I cannot think of a way to do this through JS or PHP. I can get the options posted in the php but I can't identify what options go with each attribute.
Here is a fiddle!
Here is the code to get the lengths for each of the respective options.
$('.tattribute option:selected[value="text"]').length
$('.tattribute option:selected[value="checkbox"]').length
$('.tattribute option:selected[value="select-list"]').length
$('.tattribute option:selected[value="notes"]').length
Fiddle
Here is a fiddle with a hidden field added to keep track of the options count. Every time an option is added or removed the value of the hidden field is incremented or decremented. The changes are in the code below
var template="<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attributeName[]"+"\">Name:</label>"
+ "<input class=\"attribute\" type=\"text\" name=\"attributeName[]"+"\">"
+ "<input class=\"attribute_count\" type=\"hidden\" name=\"attributeCount[]"+"\">"
+ "<label for=\"attributeType[]"+"\">Type:</label>"
+ "<select class=\"tattribute\" name=\"attributeType[]"+"\">"
+ "<option value=\"text\" selected>Text</option>"
+ "<option value=\"checkbox\">Checkbox</option>"
+ "<option value=\"select-list\">Select Option List</option>"
+ "<option value=\"notes\">Notes</option>"
+ "</select>"
+ "<div class=\"option\"></div>"
+ "<button type=\"button\" class=\"remove\">Delete</button>"
+ "</div>";
And
//Add action
$("#attributes").on('click', '.btn', function () {
add = "<div class=\"op\"><label for=\"attributeOption[]" +"\">Name:</label>"
+ "<input class=\"option-input\" type=\"text\" name=\"attributeOption[]" + "\">"
+"<button type=\"button\" class=\"remove-option\">remove</button></div>";
$(this).after(add);
//COUNT NUMBER OF OPTIONS
$opt = $(this).closest('.option')
$opt.siblings('.attribute_count').val($opt.find('.op').length)
alert($opt.siblings('.attribute_count').val());
});
//Remove input
$("#attributes").on('click', '.remove-option', function () {
$(this).closest('.op').remove();
$opt = $(this).closest('.option')
$opt.siblings('attribute_count').val($opt.find('.op').length)
});

join two html block variables in javascript

I am trying to join two blocks of html code with javascript and call a dialog afterwards. I have done some research and tried concat and + but that doesnt work. Here is a simplified version of my code:
var html =
"<div class=\"dialog-form\" title=\"Edit\">" +
"<form class=\"insertaplato\" method=\"POST\" action=\"edit.php\">" +
"<fieldset>" +
"<label>Plate: </label> <input type=\"text\" value=\"" + plate + "\" >" +
"<label>Price: </label><input type=\"text\" value=\""+ price +"\" >";
"Spicy: <br> ";
if (spicy==1)
{var varP=
"<label> Yes </label><input value= \"yes\" type=\"radio\" checked>"+
"<label> No </label><input value=\"no\"><br><br>";
} else {
var varP=
"<label> Yes </label><input value=\"yes\" type=\"radio\">"+
"<label> No </label><input value=\"no\" checked type=\"radio\"><br><br>";
}
var html2 = "<br>"+
"<br><input id=\"insert\" type=\"submit\" value=\"Edit\" name=\"send\"> " +
"</fieldset>"+
"</form>"+
"</div>";
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
As it is right now the dialog doesnt come up. If I do this with only the first html variable it come up Ok but when I try to add or concatenate the others nothing happens. I am evidently not using these variables as I should. Any ideas?
Concatenate the strings and not the jQuery objects
var div = $(html + varP + html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
Remove the $ where you're appending the pieces together. You want to append the strings into a single object.
var div = $(html + varP + html2);
intead of
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
try this:
var div = html+varP+html2;
$('.dialog-form').dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});

Categories

Resources