Unable to delete row using jquery which was dynamically created - javascript

I am creating new rows using jquery and want to delete that row when delete button is pressed. Adding new row part is working fine and the problem is in delete part. When I click on delete button then nothing happens. It doesn't even show alert which is written in code. It seems to me like delete button is not even getting pressed.
How can I delete that particular record when delete button is pressed?
JSfiddle is given below
https://jsfiddle.net/ec2drjLo/
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow">
</div>

As you have added the elements as a string, they are not valid HTML elements and that's why you can't add an event listener. You can add the click event to the document body and capture the event target, like
$(document).on('click', function (e){
if(e.target.className === 'deleteClass'){
//process next steps
}
}
You can try the demo below, not sure if it's the result you need, but the delete button works. Hope it helps!
let accountCount = 0;
$("#addAccount").click(function (e)
{
accountCount++;
let mystring = "<label class=\"ok\" id=\"[ID]\">[value]</label>";
let deleteString = "<button class=\"deleteClass\" id=\"deleteAccount"+ accountCount +"\">Delete Account</button>";
let currency = mystring.replace("[ID]", "currency"+ accountCount).replace("[value]", $("#currencyMain").val());
let amount = mystring.replace("[ID]", "amount"+ accountCount).replace("[value]", $("#amountMain").val());
$("#transactionRow").append(currency);
$("#transactionRow").append(amount);
let div = document.createElement('div');
div.innerHTML =deleteString;
$("#transactionRow").append(div);
$("#currencyMain").val('');
$("#amountMain").val('')
});
$(document).on('click', function (e)
{
if(e.target.className === 'deleteClass'){
var content = $("#transactionRow").html();
var pos = content.lastIndexOf("<label class=\"ok");
if(pos > 5)
$("#transactionRow").html(content.substring(0,pos));
else
alert("You cannot delete this row as at least one Account must be present");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow" style="border: 1px solid grey">
</div>

Related

How to make image give her name to text field then edit the name and save it? Plus delete button should remove picture

This one is very tricky and I cant imagine how to solve it... Request was "Double click on picture, then you get picture name in to text field. There you can change name and save it with button. Also there's another button which clicked you delete the picture."
At this moment I dont have much, it's just a guess what it should look like..
function rodytiViduryje(pav){
var paveikslas=document.getElementById("jap");
paveikslas.src=pav.src;
var aprasymas=document.getElementById("apr");
aprasymas.value=pav.title;
lastph=pav;
}
function keistiAprasyma(){
var NA=document.getElementById("apr");
lastph.title=NA.value;
}
function trintiPaveiskla(){
lastph.remove();
}
<div class="ketvirtas">
<!-- THIS PICTURE -->
<img id="jap" src="https://media.cntraveler.com/photos/60596b398f4452dac88c59f8/16:9/w_3999,h_2249,c_limit/MtFuji-GettyImages-959111140.jpg" alt=japonija class="b" style="width:780px;height:480px">
</div>
<div class="penktas">
<div class="aprasymas"> <!-- Buttons-->
<label for="tekstas">
<b>Paveikslo aprasymas</b>
</label><br/>
<input type="text" id="apr" />
<button id="saugoti" onclick="keistiAprasyma()">Išsaugoti aprašymą</button><br/>
<br>
<button onclick="trintiPaveiksla()">Trinti iš galerijos</button><br/>
</div>
</div>
Please share your ideas! :)
JS could be something like this (also made small changes to HTML):
document.addEventListener("DOMContentLoaded", function(event) {
let img = document.querySelector('#jap');
let descriptionInput = document.querySelector('#apr');
let saveButton = document.querySelector('#saugoti');
let deleteButton = document.querySelector('#trinti');
img.addEventListener('dblclick', function (e){
console.log
descriptionInput.value = this.alt;
});
saveButton.addEventListener('click', function(){
img.alt = descriptionInput.value;
});
deleteButton.addEventListener('click', function(){
img.remove();
});
});
<div class="ketvirtas">
<!-- THIS PICTURE -->
<img id="jap" src="https://media.cntraveler.com/photos/60596b398f4452dac88c59f8/16:9/w_3999,h_2249,c_limit/MtFuji-GettyImages-959111140.jpg" alt="japonija" class="b" style="width:780px;height:480px" />
</div>
<div class="penktas">
<div class="aprasymas"> <!-- Buttons-->
<label for="tekstas">
<b>Paveikslo aprasymas</b>
</label><br/>
<input type="text" id="apr" />
<button id="saugoti">Išsaugoti aprašymą</button><br/>
<br>
<button id="trinti">Trinti iš galerijos</button><br/>
</div>
</div>
My advice for future endeavours: scale your tasks to smaller ones. This will give you more valid results. Also you'll be able to learn while combining those multiple solutions to the one you need. I.e., your searches for this task could be:
Javascript double click event
Javascript get images' alt value
Javascript set images' alt value
Javascript remove DOM element

Clone <div> and change onclick code of inner button

I have a div with id="add-dependent" including 2 rows and a button (add dependent) inside of the div. When "add dependent" button is clicked, the first row would be cloned and insert before (add dependent) button. Actually I have another button outside of the div called (add applicant) and by clicking it, whole of the div would be cloned and added before (add applicant) button. my code is like this :
let nextLabel=2
let nextId=1
function addApplicant(){
var elem= document.querySelector("#add-dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("add-applicant");
clone.id = "add-dependent"+nextLabel;
elem.parentElement.insertBefore(clone,add);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove" onClick="$(this).parent().parent().parent().parent().remove()">x</button>' + "Applicant " + (nextLabel++) ;
}
function addDependent(){
var elem= document.querySelector(".dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("dependent");
elem.parentElement.insertBefore(clone,add);
var label=clone.querySelector('label');
label.innerHTML= '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" onClick="$(this).parent().parent().parent().remove();" >x</button>';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-dependent">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div >
<input type="number" placeholder="age">
</div>
</div>
<div class="form-row dependent">
<div>
<button id="btn" name="btn" type="button" class="close " onClick="$(this).parent().parent().remove();" >x</button>
</div>
<div>
<input type="number" placeholder="age">
</div>
</div>
<button id="dependent" onClick="addDependent()">Add dependent</button>
</div>
<button id="add-applicant" onClick="addApplicant()">Add applicant</button>
my problem is when i click on (add dependent) in cloned div, the row is added to main div not cloned one.
hope to here you soon.
Thanks a lot
There are many changes I made to your code and I'll try to explain them here. When you're working with duplicating, appending, removing etc, id's can become difficult to work with - you can't have duplicates of IDs and your code then has to track which id is affected by which button etc.
Its much easier to work with relative paths. For instance when you want to add a dependent, it's easier to say 'find a dependent input to clone and place it inside the container from where I clicked this add-dependent button' - and walla no need for ids. To find the relative div's, I used a combination of event.target, closest() and querySelctor - like this:
e.target
.closest('.add-applicant-container')
.querySelector('.dependents')
.append(clone);
This says Starting from the button I clicked, find the closest '.add-applicant-container' and inside that find the first '.dependents' and place our clone right after that
Finally, the buttons. Because you're creating and destroying these buttons in the process, it's best to set up a listener on document and test to see which button was clicked. This is called event delegation. For the dependent delete button, we only need to find the relative element and delete it so:
if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
let nextLabel = 2
let nextId = 1
document.addEventListener('click', function(e) {
if (e.target.classList.contains('add-applicant')) {
addApplicant(e)
} else if (e.target.classList.contains('btn-dependent')) {
addDependent(e)
} else if (e.target.classList.contains('remove-applicant')) {
e.target.closest('.add-applicant-container').remove()
} else if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
})
function addApplicant(e) {
let applicant = document.querySelector('.add-applicant-container')
var clone = applicant.cloneNode(true);
clone.id = "add-dependent" + nextLabel;
clone.querySelectorAll('.dependent-container').forEach((el, i) => {
if (i !== 0) el.remove()
})
applicant.parentElement.insertBefore(clone, e.target);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove-applicant">x</button>' + "Applicant " + (nextLabel++);
}
function addDependent(e) {
let dependent = document.querySelector('.dependent-container')
var clone = dependent.cloneNode(true);
e.target.closest('.add-applicant-container').querySelector('.dependents').append(clone);
// var label = clone.querySelector('label');
// label.innerHTML = '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" >x</button>';
}
.add-applicant-container{
padding:10px;
}
.dependent-container{
padding:5px 0 ;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add-applicant-container">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div>
<input type="number" placeholder="applicant age">
</div>
</div>
<div class="form-row dependent-container">
<div>
<input type="number" placeholder="dependent age"> <button id="btn" name="btn" type="button" class="close ">x</button>
</div>
</div>
<button class="btn-dependent">Add dependent</button>
</div>
<button class="add-applicant">Add applicant</button>

alert box sequence after an image has been loaded

So I am trying to create pop up logic for a simple find an object game. So I created a an array of strings that I want to display 2 alert messages. The first alert stating hey you found [insertName].Then if you click on the same object again it display a generic message "you already found this". Then after all images have been clicked, I have a new page loaded based of the int count of items clicked. What I'm having trouble with is how to execute that first initial alert. I was thinking I would create another array for the initial alerts,but that when i got stuck.
<div id="b1" class="mybox">One</div>
<div id="b2" class="mybox">Two </div>
<div id="b3" class="mybox">Three </div>
<div id="b4" class="mybox">Four </div>
<div id="b5" class="mybox">Effortless Calls </div>
<div id="b6" class="mybox">Voicebot </div>
<script type="text/javascript">
//$('body').css('background','blue');
var Boxes = [];
var ttle = $('.mybox').length;
$('.mybox').click(function () {
alert('Blah ');
var bx = this.id;
if (Boxes.indexOf(bx) >= 0){
alert('You Already Found Object ');
}else{
Boxes.push(bx);
}
if (Boxes.length ==ttle)
window.location = "#/finishedgame";
});
</script>
Add a custom attribute to the your elements data-clicked="false"
When the user clicks the element set elem.setAttribute('data-clicked','true');
<div id="b1" class="mybox" data-clicked="false">One</div>
<div id="b2" class="mybox" data-clicked="false">Two </div>
<div id="b3" class="mybox" data-clicked="false">Three </div>
<div id="b4" class="mybox" data-clicked="false">Four </div>
<div id="b5" class="mybox" data-clicked="false">Effortless Calls </div>
<div id="b6" class="mybox" data-clicked="false">Voicebot </div>
$('.mybox').click(function (elem) {
var clicked = $(elem).data('clicked');
if(clicked){
alert(msg1);
} else {
alert(msg1);
elem.setAttribute('data-clicked','true');
};
});
You don't need another array, before you do Boxes.push(bx); why don't you just do alert(hey you found [insertName]);? this should be the first time a user is touching a box aka when you want the first alert at least from what I gathered from your post. So
var Boxes = [];
var ttle = $('.mybox').length;
$('.mybox').click(function () {
var bx = this.id;
if (Boxes.indexOf(bx) >= 0){
alert('You Already Found Object ');
}else{
var text = [get name of box here]
alert("hey you found" + text);
Boxes.push(bx);
}
if (Boxes.length ==ttle)
window.location = "#/finishedgame";
});

change displayed div with Javascript

I've been trying to get this to work and thought it would be relatively easy but i'm just unable to target my div's with javascript.
I want a list of boxes and each one will be clickable and each one has a buddy which is hidden. when you click a , it hides and shows its buddy which will have an input box. Type the text in you need and press ok and it changes back to it's original displaying the text you have entered.
the head contains the following:
<head>
<script language="javascript">
var state = 'none';
function showhide(layer_ref) {
if (state == 'block') {
state = 'none';
}
else {
state = 'block';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.display = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].display = state;
}
if (document.getElementById &&!document.all) {
hza = document.getElementById(layer_ref);
hza.style.display = state;
}
}
</script>
And then my HTML contains:
<div id="div0">
<a href="#" onclick="showhide('div1');" style="text-decoration:none;">
<div style="width:200px; height:30px; background-color:grey;color:white">
Input: <div id="showinput"></div>
</div>
</a>
</div>
<div id="div1" style="display:none;">
<div style="width:200px; height:30px; background-color:grey;color:white">
<input type="text id="addInput" /">
<input type="submit" value="submit" name="submit" onclick="showhide('div1');" />
</div>
</div>
I'm trying to add the following but it just won't update the original and the script just makes the buddy div show below the original. How can i hide the original at the same time?
var myobj = document.getElementById("addInput");
var mytext = myobj.value;
document.getElementById("showinput").innerHTML = mytext;
You are missing a closing quote around type="text so the input id is not set. Try:
<input type="text" id="addInput" />

Pass js var into html block being added via appendTo

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!
you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});
add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});
Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Categories

Resources