Prevent delete of last div in Javascript - javascript

I have a slight problem in a feature I am trying to implement on a web page. I have two images, a plus and a minus sign, when plus is clicked it clones a div which consists of a few text box's. The minus image is meant to delete this div.
At the moment, I cannot seem to find a way to stop the last div from being deleted when I click on the minus. I want to just prevent the last row from being deleted and using an alert to inform the user that it cannot be deleted.
Can anyone give me some insight to this? I've searched on here for a while and found something similar, but it's all done using JQuery which I have no experience with.
Here is the code I am using to try and delete the div's.
function deleteRow1() {
// row-to-clone1 is the name of the row that is being cloned
var div = document.getElementById('row-to-clone1');
if (div) {
div.parentNode.removeChild(div);
}
if ((div).length != 1) {
alert("Cannot delete all rows.").remove();
}
}
When I try do delete the row it displays the alert but still deletes the div. I realise this is probably a very easy fix and my implementation of the above may not be correct, if anyone can help I would appreciate it.

ID of an element must be unique, so use a class to fetch them
function deleteRow1() {
// row-to-clone1 is the name of the row that is being cloned
var divs = document.getElementsByClassName('row-to-clone1');
if (divs.length > 1) {
divs[0].parentNode.removeChild(divs[0]);
} else {
alert("Cannot delete all rows.")
}
}
function add1() {
var div = document.getElementById('row-to-clone1');
if (div) {
var clone = div.cloneNode(true);
delete clone.id;
div.parentNode.appendChild(clone);
}
}
<button onclick="add1()">Add</button>
<button onclick="deleteRow1()">Delete</button>
<div id="row-to-clone1" class="row-to-clone1">div</div>

Related

How to edit elements created with javascript via a loop when click/hover

Can anyone help me? I have many HTML buttons created with Javascript. I want them to delete itself on onclick and change its CSS while hovering your mouse over it, but the "newButton" variable stores the last element from localStorage, which is the last button. With my code, I can only edit the last button. I want the other buttons to delete itself on onclick and change its CSS on hover. I have tried
newButton.onclick=function() {
document.getElementById("list").removeChild(newButton);
localStorage.removeItem(newButton);
}
but it doesn't work well. It only will remove the last button. Although it does, it doesn't remove it from local storage. By the way, the variable "list" is a
< div >, not a < ul >.
Javascript
var list= document.getElementById("list");
function addItemToLocalStorage(){
var newKey=prompt("What key do you want to add to your local storage?");
var newItem=prompt("What value does the key have?");
if (newKey && newItem){
localStorage.setItem(newKey,newItem);
location.reload();
}
}
window.onload=function(){
for (i=0; i<localStorage.length ; i++){
var key=localStorage.key(i);
var lcStorage=localStorage.getItem(key);
var newButton= document.createElement("button");
document.getElementById("list").insertAdjacentElement("beforeend",newButton);
newButton.innerHTML=key+" : "+lcStorage;
newButton.style.padding="20px";
newButton.style.border="lightgray";
newButton.style.fontSize="20px";
newButton.onclick=function(){
list.removeChild(newButton);
localStorage.removeItem(newButton);
}
}
}
If you need anything else just ask me.

loop through and remove form elements in Javascript

Hi I have been writing a Javascript quiz whilst learning Javascript, but have encountered a problem.
I have one function that dynamically creates the question/answers with radio buttons to mark off the questions.
When I use this second function to attempt to remove the question/answers so I can show the new ones; it removes the text (in p tags) but doesn't remove the radio buttons, even though they also show as children to the form element.
function removeLastQuestions() {
var allQuestions = document.getElementById('questionForm');
for (var i = 0; i < allQuestions.children.length; i++) {
allQuestions.removeChild(allQuestions.children[i]);
}
}
The question/answers and buttons are contained within a form with the id of "questionForm"
I guess I could put the whole form within a div and remove the form, but I'm wondering why looping over them isn't working. I'm trying to do it without using Jquery.
Thanks for any help.
Try this way:
var node = document.getElementById('questionForm');
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
This will remove all form elements.
JSFiddle demo

Can someone help me apply the js 'this' keyword to an iterated jq select expression

Here's my latest version of this code. The 1st line iterates through the rows of a table skipping over the 1st row. For each row I test to see if the (class='dim') state of one of 8 tag elements (index j) on that row matches the corresponding !'dim' state of a set of 8 filters that the user can toggle. The idea is to set any rows where the 'active' filter / 'dim' tag states line up, to the 'hide' class, so they can disappear from the table that the user sees. The CSS for disappearing it is: .hide {display:none;}
It's that last 'if' statement that's killing me. I've tried dozens of versions but I always get some form of syntax error, undefined variable, etc. In that line of code here I've removed my latest set of +, ', " characters to better show clearly what I'm trying to do.
I don't just want something that works to replace this code. And I'm not interested in the shortest trickiest way to do it. I'd like to see some simple obvious code that I could easily understand a year from now so I can solve problems like this myself. Thanks in advance.
var thisRow = $('tbody tr:gt(0)').each(function() {
for (var i=0,j=4;i<8;i++,j++) {
if (!$('.butt').eq(i).hasClass('dim')) {
if (thisRow.nth-child(j)).hasClass('dim')) $(this).addClass('hide');
else $(this).removeClass('hide');
}
}
}
Above this line is the question as I first asked it. Below this is the complete function in case anyone else might find this useful. Thanks to Mr. Pavlikov for the lesson!
function filterTbl() { //Hide rows that don't satisfy all active filters
var butts=$('.butt'); //Each filter button has class 'butt'
$('tbody tr:gt(0)').each(function() { //iterate each table row except the 1st
var thisRow = $(this); //the row being examined
var chilluns = thisRow.children(); //all td's in the row being examined
for (var i=0,j=4;i<8;i++,j++) {
if (!butts.eq(i).hasClass('dim')) { //If this filter is active
//and If the corresponding tag is not active (is 'dimmed'), then hide this row
if (chilluns.eq(j).hasClass('dim')) thisRow.addClass('hide');
else thisRow.removeClass('hide'); //else unhide this row
}
}
});
}
First of all you should be getting thisRow variable like this (not like you are currently doing)
$('tbody tr:gt(0)').each(function() {
var thisRow = $(this);
}
And what does nth-child stand for? Use nth-child selector correctly or use siblings at least if you are willing to compare one row with other rows. I didn't quite understand what are you trying to do, but hope this helps.
And some usefull tips. You do not need to find $('.butt') EVERY TIME in the loop, just find it once before your each loop:
var butts = $('.butt');
So now you will be able to replace
$('.butt').eq(i)
with
butts.eq(i)
This is significant speedup.
Also if n-th child you are trying to find is something that is inside thisRow, find children and do .eq() on them.

Changing name of all classes in html document with javascript

I have a List that shows Products. When I click on one, I need to change the class of the <li> so as to show that it is clicked. I got this working... But what I can't do is clear the other <li> that have been previously clicked so as to show it is not selected anymore.
This is part of my code, what am I doing wrong? btw, my logic here is to first refresh all classes to notselected, and then just update the list with my product id number. this can be seen on the second line of code.
I'm new to javascript, and did my research, and this is what I got.
function showdetails(ProductID) {
document.getElementsByName("ProductList").className = "notselected";
$("#"+ProductID).attr('class','selected');
Are you trying to do this?
function showdetails(ProductID) {
$("[name=ProductList].selected").removeClass('selected');
$("#"+ProductID).addClass('selected');
}
I think you need to iterate across all elements returned in document.getElementsByName("ProductList") and change className to each element individually.
var productLists = document.getElementsByName('ProductList');
for (i = 0; i < productLists.length; i++) {
productLists[i].className = 'notselected'
}

appending a div at the end of a dynamically created row

I have rows that are dynamically created and I want to append a div at the end of each row. I tried different ways to get this to happen. one time I ended up appending the div to each row but the previous rows got additional divs every time a row was added. I want only one row to have 1 cancel div at all time. (this will be like a cancel button so the user can delete the row).
in this code i am trying to go through each row with the class of row and check to see if the row has a child with a class of "cancel" and if there is none append the div cancel. It works the first time but not the other times.
$('.row').each(function(){
if($(".row").children(".cancel").length == 0){
$("<div class = 'cancel'>test</div>").appendTo('.row')
}
})
I tried to add the div "cancel" in the else statement when I append the rows like this
if($(".table").html().length <= 0)
{
$('.table').append($("<table>").append(tableheader).append(tr));
}else{
if($(".table").html().length > 0){
$("table").append(tr).append("<div class = 'cancel'>test</div>")
}
}
but it didn't show up at all
I know I could probably add another td to the var tr to make a new column with the div, but I'm wondering why my efforts to doing it the above way was a unsuccessful. It should work. excuse my ignorance .
here is the jsfiddle for illustration. maybe there is something wrong with the code somewhere else.
I have another problem in the code that I think that you could help me out with. Its with the total amount in the total column. the format is coming out as 7.5 instead of 7.50, normal dollar pricing figures. and when im on grilled chicken cutlet and choose qnty = 3 the total is 38.849999999999994 i thought toFixed(2) and parseFloat would fix that but they didn't work. obviously I would like 38.85.
I think the problem is in the way you are accessing the table rows while appending the div.
$('.row').each(function(){
if($(".row").children(".cancel").length == 0){
$("<div class = 'cancel'>test</div>").appendTo('.row')
}
});
The above script always searches for the class .row while appending the div. So if you have a div appended to any one of the .row class, if condition fails.
Solution:
To fix the problem, use $(this) to access the each row in the loop.
$('.row').each(function(){
if($(this).children(".cancel").length == 0){
$("<div class = 'cancel'>test</div>").appendTo($(this))
}
});
Also to fix your second issue of price, change
$(".total",$row).html(parseFloat(qnty * price));
to
$(".total",$row).html(parseFloat(qnty * price).toFixed(2));
Check the updated Demo Fiddle.
try this:
$('.row').each(function(idx, val){
if($(val).children(".cancel").length == 0){
$("<div class = 'cancel'>test</div>").appendTo(val);
}
});
you can do this
a)console.log($('.row').length)// to see the length
$("test").appendTo('.row') //this.code should "$("test").appendTo($(this)) "
I think what i say above may helpful; try your self

Categories

Resources