So I'm working on creating a web app that allows users to create a front end theme for a website; I'm mostly doing this to better my JS skills.
What I'm doing in the code below is creating "boxes" that span the width of the page, and I want to allow the user to edit each individual box.
The issue I'm facing is I can select the class/id that the user clicked along with the div I have set up for all the elements that the user wants; however I cannot seem to attach any DOM methods onto the object.
Errors are Uncaught TypeError: Object editBoxes has no method 'innerHTML' where 'innerHTML' can be any method. I've also tried Jquery's .html with the same result.
for(i=1; i <= boxes; i++) {
box.innerHTML = box.innerHTML + [
"<div class = 'globalBox' id = 'box"+i+"'>",
"<div class = 'editDyBox'>edit this box <div class = 'editBoxes'></div<!--end edit boxes--></div>",
"</div><!--end box-->",
].join('');
}//end for
$(".globalBox").css("width", width+"%");
$(".editDyBox").click(function(){
var parentClass = $(this).parent().attr("id");
var childClass = $(this).children().attr("class");
var customEdit = $(this).attr("class");
var editBoxForm = "<form class = 'editBoxForm'><input type = 'text' name = '"+parent+"' width = '100%'></form>";
childClass.innerHTML("hello")
});//end editdybox click
Thank you
-Art
Why don't you use contenteditable instead of your complex code?
It's designed for that.
Check out this Demo
<div contenteditable="true">I'm the content</div>
It's supported by ALL browsers (yeah, even IE5)
its a normal div, so it spans all the available width, and his content is editable. No JS or CSS nedded.
This line returns a string, not a jQuery object
var childClass = $(this).children().attr("class");
So your variable childClass is going to just be a simple string object. It will never have the method innerHTML.
Additionally, this will return only the first child's class value and not an array of class values.
What about using one click handler per element?
var boxes = 3;
var $boxes = $("#boxes");
$.each(new Array(boxes), function () {
var box = $("<div/>").appendTo($boxes),
editBox = $("<div/>").text("edit this box").appendTo(box),
editBoxForm = $("<div/>").appendTo(editBox);
editBox.click(function () {
editBoxForm.html("hello");
});
});
jsFiddle Demo
Remove this
childClass.innerHTML("hello")
By this
$(this).children().innerHTML("hello");
Related
I'm quiet new above all on Javascript technology. I want to create various div according to the number of string into an array of checked checkboxes but after my code it only displays one div every time... I must go through a jquery dialog to display it !
My JSP
<div style="overflow: scroll;" id="listCurrentContact"></div>
My listContact.js
varPopup = $('#dialogMultiplesDeleteConfirmation').dialog({
resizable : false,
modal : true,
autoOpen : false,
width : 500,
open: function(){
var SuppressCheckboxItems = [];
// I put into an array the different value of checked checkboxes
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
SuppressCheckboxItems.push($(this).val());
});
var z = document.createElement('div');
// I suppress the ',' between each element
var test = SuppressCheckboxItems.toString();
var tab = test.split(",");
for(var i = 0; i < tab.length; i++){
z.innerHTML = tab[i];
$('#listCurrentContact').html(z);
}
Have you tried using .append instead of .html while concatenating your checkboxes to #listCurrentContact.
You can refer this document: https://www.w3schools.com/jquery/html_html.asp to see that .html() replaces the previous content with the new content whereas what you are trying to achieve here is appending the entire array of values to the div. Look at how .append() works in this link : https://www.javascripttutorial.net/javascript-dom/javascript-append/. Just to give you a brief overview, when you write a .append() on any element, it doesnot replace the previous content with the new content but instead attaches/concatenates the new content after the previous content.
You should use $('#listCurrentContact').append(z);
Thanks to SaloniMishra Ive found the good answer. It just needed to change the .html() to .append() but with that if the customer just quit the jquery dialog and retry the previous elements stayed in the div so you need to clean every elements before to relaunch the function with the function removeChild()! Thanks all !
open : function() {
var SuppressCheckboxItems = [];
const currentDiv = document.getElementById('listCurrentContact');
while (currentDiv.firstChild) {
currentDiv.removeChild(currentDiv.lastChild);
}
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
var z = document.createElement('div');
z.innerHTML = $(this).attr("name");
$("#listCurrentContact").append(z);
});
I am having a bit of trouble finding what is wrong with my code, it is supposed to display a hidden popUp when I click a link (id= lnkInfo) on a div, the problem is that it only works for the first div and not for the others on a list.
This is the code I was using to hide nd display:
JS
function displayPopUp(pIdDivToShow){
var fElementDivToShow = document.getElementById(pIdDivToShow),
newClass ='';
newClass = fElementDivToShow.className.replace('hide','');
fElementDivToShow.className = newClass + ' show';
}
function hidePopUp(pIdDivToShow){
var fElementDivToShow = document.getElementById(pIdDivToShow),
newClass ='';
newClass = fElementDivToShow.className.replace('show','');
fElementDivToShow.className = newClass + ' hide';
}
Said divs are created via php, as does the information that goes inside the pop up, so to show exactly what is going on I made a fiddle out of it with how it would look when I have two divs, the id of the lab divs is always the last one's id+1.
Fiddle EDITED
I know that I should use a class instead of a id, but doing so makes the JS part to malfunction, even if I use querySelector or getByClass.
Any help would be deeply appreciated! Thanks in advance.
EDIT:
So I was thinking something along these lines to do what was suggested and apply the changes to each element. Prettu sure that is not how I attach the array to the displayPopUp thou.
var elementoVerInfo = document.getElementsByClassName('lnkInfo'),
elementoBotonCerrar = document.getElementById('btnCerrar');
elementoVerInfo.addEventListener('click', function () {
for (var i = 0 ; i < elementoVerInfo.length; i++) {
elementoVerInfo[i].displayPopUp('popUpCorrecto1');
};
});
ID's must be unique.
You will have to change the id to a class and use something like document.getElementsByClassName
I'm currently building a small Todo list application using vanilla Javascript but I'm having some issues creating a delete button that onClick removes it's parent element.
From what I have read, when an onClick is called in Javascript the this keyword can be used to refer to the element that called the function. With this in mind I have the following code:
window.onload = initialiseTodo;
function addRecord(){
var title = document.getElementById('issueTitle');
var issueContent = document.getElementById('issueContent');
var contentArea = document.getElementById('contentArea');
if(title.value.length > 0 && issueContent.value.length > 0){
var newItem = document.createElement('div');
newItem.id = 'task' + count++;
newItem.className = 'task';
newItem.innerHTML = '<div class="taskbody"><h1>' + title.value + '</h1>'+ issueContent.value + '</div><div class="deleteContainer">'
+ '<a class="delete">DELETE</a></div>';
contentArea.appendChild(newItem);
assignDeleteOnclick();
}
}
function deleteRecord(){
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
function assignDeleteOnclick(){
var deleteArray = document.getElementsByClassName('delete');
for(var i=0;i<deleteArray.length;i++){
deleteArray[i].onclick= deleteRecord();
}
}
function initialiseTodo(){
var btn_addRecord = document.getElementById('addRecord');
btn_addRecord.onclick = addRecord;
}
Basically I have a form that has two fields. When these fields are filled and the addRecord button is clicked a new div is added at the bottom of the page. This div contains a delete button. After the creation of this I assign an onclick event to the delete button which assigns the deleteRecord function when the delete button is clicked. My issue is with the deleteRecord function. I have used this to refer to the calling element (the delete button) and wish to remove the task div that is the outermost container however I current get a message that says: 'Cannot read property 'parentNode' of undefined ' which suggests to me the this keyword is not working correctly.
Any help would be greatly appreciated.
I've added the full code to a fiddle.
http://jsfiddle.net/jezzipin/Bd8AR/
J
You need to provide the element itself as a parameter. I did so by changing the html to include onclick="deleteRecord(this)" to make it a little easier to deal with. This means you can remove the assignDeleteOnclick() function
function deleteRecord(elem){
elem.parentNode.parentNode.remove();
}
Demo
You might style the .content to be hidden better if there are no elements to prevent that extra white space
Edit
Since you don't want an inline onclick, you can do it with js the same:
function deleteRecord(elem){
elem.parentNode.parentNode.remove();
}
function assignDeleteOnclick(){
var deleteArray = document.getElementsByClassName('delete');
for(var i=0;i<deleteArray.length;i++){
// Has to be enveloped in a function() { } or else context is lost
deleteArray[i].onclick=function() { deleteRecord(this); }
}
}
Demo
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');
I have some data coming from the server in which I fill A Div in the Html page with.
The way I write the div is as follows:
<div class="BigDiv"><label class = "AttList" Std_Id="' + Std_Id + '">' + Std_Name +'</label></div>
Now, I want the data inside this div.
There are some other labels inside the div so I use this.children to access this label.
var labels = $(this).children('div');
var StdName = this.children[0].childNodes[0].nodeValue;
I want to access the Std_Id inside the Std_Id attribute, but I don't know how to do it ... Do you have any ideas?
Thanks.
Assuming that $(this) is a reference to the .BigDiv element:
var StdName = $(this).find('label').attr('Std_Id');
Or, similarly, and with the assumption that this is the .BigDiv element:
var children = this.childNodes;
for (var i=0,len=children.length; i<len; i++){
if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == 'label'){
var StdName = this.getAttribute('Std_Id');
}
}
References:
jQuery:
attr().
find().
JavaScript
element.getAttribute().
node.nodeType.
tagName.
toLowerCase().
Use getAttribute:
var labels = $(this).children('div');
var StdId = this.children[0].getAttribute("Std_Id");
Note that, according to the HTML5 spec, custom attributes should start with data-, though most browsers can tolerate it.
To save elements, which were selected using a jQuery-Selector, do this:
$labels = $('.BigDiv').find('label');
Now you can loop through each label with jQuery's foreach loop:
$.each($labels, function() {
var std_id = $(this).attr('Std_Id');
// do something with std_id
});
You could use the attr method as such,
var value = $('.AttList').attr('Std_Id');
EDIT
OK, so you for your implementation, you need to do this...
var value = $(this).find('.AttList').attr('Std_Id');
Assuming that this is the div or the parent of that div