Get content of a DIV using JavaScript - javascript

I have two DIV's called DIV1 and DIV2 and DIV1 consists of dynamic content and DIV2 is empty. I need content of DIV1 to be displayed in DIV2. How can I do it.
I coded in below manner which is not working. Anybody please correct it.
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('Div2');
MyDiv2.innerHTML = MyDiv2;
</script>
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
</body>

(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>

You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Here is a JSFiddle: http://jsfiddle.net/gFN6r/.

Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById is case sensitive. You were passing Div2 when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}

simply you can use jquery plugin to get/set the content of the div.
var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );
for this you need to include jquery library.

function add_more() {
var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';
for (i = 1; i <= count; i++) {
var cmp_text = document.getElementById('cmp_name_' + i).value;
var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
divContent += '<div id="div_cmp_' + i + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
'</div>';
}
var newCount = count + 1;
if (document.getElementById('div_cmp_' + newCount) == null) {
var newText = '<div id="div_cmp_' + newCount + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>' +
'</div>';
//content = div_cmp.innerHTML;
div_cmp.innerHTML = divContent + newText;
} else {
document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>';
}
document.getElementById('text_count').value = newCount;
}

Related

jQuery pass object in inline onclick

How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>

select element with class and id with jquery

I'm trying to select two different elements with class and id, the first works but the second doesn't (it works without the id), I can't figure out why.
help me, please.
code:
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("main").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"" + num.toString() + "\"></p>\
</div>\
</div>");
var title = $("#noteTitle").val();
var body = $("#noteBody").val();
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#"+ num.toString()).html(title);
$(".card-text#"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
Here you go with the solution . https://jsfiddle.net/0knefedh/
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("body").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"title" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"text" + num.toString() + "\"></p>\
</div>\
</div>");
var title = "dasdasd";
var body = "asdasdas";
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#title"+ num.toString()).html(title);
console.log(num);
$(".card-text#text"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="add" value="Add" >Add</button>
Problem is with ID that you are generating for .card-title and .card-body. Both are having same ID, where as ID should be unique.
So, it work for the first time then it didn't.

Create input on button clicked with angularJS

I am building a website and I need to create inputs dynamically. I currently have a button and it is pressed by the user, a text input is created with an appropriate span that I set (using the class, ids, style and all that) and add it to a div (lets say a list of input(s) in same div).
Now I want to do it with AngularJS.
Can someone show me example of code that creates the input dynamically?
Here is the start:
<script></script>
<div id="AddBtn" style="border-radius: 5px; border: 0px; background-color: #982222; color: #fff; font-size: 18px;" onclick="AddRowExample()">Add +</div>
<div id="listExample">
</div>
I want learn the how to do it the angular way. I already tried to create the input dynamically but it doesn't work. I seem to be getting $compile is not defined. I tried to figure out how to inject the $compile service but it didn't work.
After Edit:
Here is the code in my system:
js:
function getDefaultAmount(lines_number){
var defaultAmount = document.createElement("div");
defaultAmount.id = "AmountValue_" + lines_number;
defaultAmount.setAttribute("class", "inlineBlock amountValueStyle");
defaultAmount.setAttribute("ng-app", "myApp");
defaultAmount.setAttribute("ng-controller", "myCtrl");
var amountInput = document.createElement("input");
amountInput.setAttribute("type", "text");
amountInput.setAttribute("class", "inlineBlock");
amountInput.setAttribute("placeholder", "???? ????");
amountInput.setAttribute("ng-model", "firstName");
defaultAmount.appendChild(amountInput);
var amountVal = document.createElement("div");
amountVal.id = "AmountVal_" + lines_number;
amountVal.setAttribute("class", "inlineBlock");
amountVal.setAttribute("ng-bind", "{firstName}");
defaultAmount.appendChild(amountVal);
return defaultAmount.outerHTML;
}
and here is the function that called to ^:
function createNewRow(line_number){
var lines_number = line_number;
var lines_place = document.getElementById("EditLinesPlace");
if (lines_number < 19) {
//-----Start build line elements
//Create the line
var line = document.createElement("div");
line.id = "Line_" + lines_number;
line.style.cssText = "border-top: 1px solid #dddddd;";
var addClass = document.createAttribute("class");
addClass.value = "lineNum width100 padding2_0 inlineBlock";
line.setAttributeNode(addClass);
lines_place.appendChild(line);
/*//Create break line*/
//Create the category place in the line
var category = document.createElement("div");
category.id = "Category_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "categoryStyle";
category.setAttributeNode(addClass);
category.innerHTML = '<div class="categoryBtn" onclick="openPopup(window.current_category,window.actions_list[0],'+ lines_number +');">' + "??? ???????" + '</div>' + getDefaultCategory(lines_number);
line.appendChild(category);
/*//Create break line*/
//Create the date place in the line
var date = document.createElement("div");
date.id = "Date_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "dateStyle";
date.setAttributeNode(addClass);
date.innerHTML = "?????: " + getDate(lines_number);
line.appendChild(date);
/*//Create break line*/
//Create the amount place in the line
var amount = document.createElement("div");
amount.id = "Amount_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "amountStyle";
amount.setAttributeNode(addClass);
amount.innerHTML = '<span class="inlineBlock">' +"???? :"+ '</span>' + getDefaultAmount(lines_number);
$compile(amount)($scope);
line.appendChild(amount);
/*//Create break line*/
//Create the repeated place in the line
var repeated = document.createElement("div");
repeated.id = "Repeated_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "repeatedStyle";
repeated.setAttributeNode(addClass);
repeated.innerHTML = '<div class="repeatedBtn" onclick="updateRepeated(' + lines_number + ')">' + '<span class="floatA">???????? : ' + getDefaultRepeated(lines_number) + '</span></div>';
line.appendChild(repeated);
/*//Create break line*/
//Create the note place in the line
var note = document.createElement("div");
note.id = "Note_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "noteStyle";
note.setAttributeNode(addClass);
note.innerHTML = "????? : " + getDefaultNote(lines_number);
line.appendChild(note);
/*//Create break line*/
//-----End build line elements
window.line_number++;
}
else {
var error = document.getElementById("ErrorPlace");
error.innerHTML = '<div class="" style="">???? ?????? ???????? ??? 20</div>';
return window.line_number;
}
}
This gives me $compile is undefined.
you could ng-repeat your inputs, and then just add another item to that model you're repeating
http://plnkr.co/edit/TXZNcq?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.inputs = [0];
$scope.moreInputs = function(){
console.log('added an input');
$scope.inputs.push(0);
};
});
html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="input in inputs track by $index">
<input type="text">
</div>
<button ng-click="moreInputs();">+ input</button>
</body>
</html>

called the javascript function onload and on button click?

i found this javascript is called by a button
but i want it to be onload at the same time , when button click it will call this javscript as well
but i not sure how? hopefully anyone of you can help out
function AddFileUpload()
{
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
<body onload="AddFileUpload();">
You can call javascript on load using jquery.
$(document).ready(function() {
var div = document.createElement('DIV');
div.innerHTML = '';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
});

onclick event is not firing in anchor tag in firefox 4.1

var ni = document.getElementById("fileDiv");
var objFileCount = document.getElementById("fileCount");
var num = (document.getElementById("fileCount").value - 1) + 2;
objFileCount.value = num;
var newdiv = document.createElement("div");
var divIdName = "file" + num + "Div";
newdiv.id = divIdName;
//newdiv.setAttribute("id", divIdName);
newdiv.innerHTML = '<input type="file" name="attachment" id="attachment"/> <a name="#" onclick="removeFile(' + divIdName + ');" style="color:blue;cursor:pointer;">Remove</a> ';
ni.appendChild(newdiv);
function removeFile(divName) {
alert(divName);
var d = document.getElementById("fileDiv");
d.removeChild(divName);
}
You forgot the quotes for the divIdName:
newdiv.innerHTML = '<input type="file" name="attachment" id="attachment"/> <a name="#" onclick="removeFile(\'' + divIdName + '\');" style="color:blue;cursor:pointer;">Remove</a> ';
Also, please elaborate more on your problem when posting a question; don't just post the code and expect an answer.

Categories