Remove one of the added lines on click - javascript

I want to only remove the line of the specific .delete that I press. How can I specify that in jQuery. Now it's removing all the p since I've chosen that as the value but I can't figure out how to make it specific for each line of append.
HTML
<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<p class="title">Amount</p>
<p class="title">Product</p>
<p class="title">Price</p>
<div>
<input class='amountInput' type='number' name='quantity' min='0' max='1000' step='1'>
<input class='productInput' type="text" name="message" value="">
<input class='priceInput' type='number' name='quantity' min='0' max='1000000' step='0.01'>
<button class="food">Add</button>
</div>
<div class="messages">
</div>
</div>
</div>
<div class="totalPrice">
</div>
jQuery
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = $frm.children(".priceInput").val();
var addAmount = $frm.children(".amountInput").val();
var div = $("<div>");
div.append("<p>" + addAmount + "</p>", "<p id='product'> " + toAdd + " </p>", "<p>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
});
});
$(document).on('click', '.delete', function() {
$('p').remove()
});

If you want to remove the elements that are being added, you'll just need to use $(this) within your function to refer to the element that triggered the call :
// When an element with the delete class is clicked
$(document).on('click', '.delete', function() {
// Remove the closest <div> above the element that was clicked
$(this).closest('div').remove();
});
If you want to update pricing...
When you remove your elements, you may want up consider updating your pricing as well, which you can do by reading your last element and subtracting it :
$(document).on('click', '.delete', function() {
// Get the previous element which contains your price
var priceToSubtract = parseInt($(this).prev().text());
// Subtract the price
totalPrice -= priceToSubtract;
// Update your price
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest('div').remove();
});
This will require you to scope your totalPrice variable outside of your $(document).ready() block as seen below :
<script>
var totalPrice = 0;
$(document).ready(function() {
// Your code here
});
</script>

You should remove the parent div of the all the p, like:
// This is delegated event as the HTML element is added dynamically
$(document).on('click', '.delete', function() {
$(this).closest("div").remove(); // .closest will traverse upwards to find the matched element that is div
});
Note: You need to use event delegation as the HTML elements are added dynamically. Learn more about it here.

Related

Unable to update global variable using javascript on button click

I need to update the price global variable. I believe it may have something to do with scope. I would appreciate it if you could be of assistance in this regard.
This is the script:
var price = 0;
var nextdayClass = $('.delivery1');
var $standardClass = $('.delivery2');
var $pickupClass = $('.delivery3');
nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday;
console.log(price);
});
standardClass.on('click', function () {
var standard = $('#standard').data('price');
price = standard;
console.log(price);
});
pickupClass.on('click', function () {
var pickup = $('#pickup').data('price');
price= pickup;
console.log(price);
});
console.log(price);
cartTotalHTML += '<div>' +
'<ul>' +
'<li>' +
'<div>Subtotal</div>' +
'<div>' + formatMoney(total) + '</div>' +
'</li>' +
'<li>' +
'<div>Shipping</div>' +
'<div>' + formatMoney(price) + '</div>' +
'</li>' +
'<li>' +
'<div>Total</div>' +
'<div>' + totalAfterShipping(total, price) + '</div' +
'</li>' +
'</ul>' +
'</div>';
$('#cartOutput').html(cartItemHTML);
Here is the html where i am getting my data from:
<div class="delivery">
<div>Shipping method</div>
<div>Select the one you want</div>
<div class="delivery_options">
<label>Next day delivery
<input id="nextday" type="radio" name="radio" data-name="nextday" data-price="9000">
<span class="checkmark delivery1"></span>
<span class="delivery_price">R90</span>
</label>
<label>Standard delivery
<input id="standard" type="radio" name="radio" data-name="standard" data-price="3000">
<span class="checkmark delivery2"></span>
<span >R30</span>
</label>
<label>Personal pickup
<input id="pickup" type="radio" checked="checked" data-name="pickup" data-price="0" name="radio">
<span class="checkmark delivery3"></span>
<span >Free</span>
</label>
</div>
</div>
Here is the html where i am taking my data to:
<div class="col-lg-6 offset-lg-2">
<div class="cart_total">
<div>Cart total</div>
<div>Final info</div>
<div id="cartTotalOutput">
</div>
<div><input type="submit" class="button checkout_button"></div>
</div>
</div>
</div>
There's two issues here. Firstly add() is to add an element to a collection, not to attach an event handler. To do what you want use click() or on().
Secondly, price is only updated after the click event happens, yet your logic is attempting to read it immediately. To address this you need to put the console.log() line in that event handler. Try this:
var price = 0;
var $nextdayClass = $('.delivery1');
$nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday;
console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="delivery1">Click me</button>
<div id="nextday" data-price="1.99">Next day: 1.99</div>
It's also worth noting that you should avoid the use of global variables where possible. A better pattern to use would be just retrieve the data attribute which holds the price where it's actually needed and remove the price variable completely.
It has nothing to do with scope.
Look at your code:
You get an element
You say that when you click the element price should be updated (well, you try to, you made a typo and called add instead of on)
You look at price
Presumably, at some point later, you click the element.
At this point price is updated.
You don't look at it again.
JavaScript does not time travel into the past and change price before you looked at it the first time.
The record of what the value was when you looked at it that is displayed in the console will not change.
If you want to log the value after you click on the element, you have to put the code that does the logging in the function that is called when you click on the element.
var price = 0;
var nextdayClass = $('.delivery1');
nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday; // The window object stuff is a waste of time
console.log("Clicked value", price);
});
console.log("Initial value", price);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="delivery1">5</button>
<span id=nextday data-price=5></span>
Try JQuery on() like this, also as I assume your element may be generated dynamically, try to bind the event handler to the body element/
var price = 0;
var nextdayClass = $('.delivery1');
$('body').on('click', nextdayClass, function() {
var nextday = $('#nextday').data('price');
window['price'] = nextday;
});
console.log(price); //Prints out 0

How to add a function to an appended element

I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});

How to show hide specific div in table?

HTML:-
'<td>' + item.Message + ' <input type="button" class="btn btn-info" id="' + item.LogID + '" onclick="Clicked(this);" value="View More" /> <p> ' + item.FormattedMessage + ' </p></td></tr>'
this is button in table
Jquery:-
function Clicked(e)
{
var SelectedID = e.id;
$("p").toggle();
};
In this When i click on button i want to show selected id column only and hide rest columns.
But when i click on button it shows all column or hides all column
In addition to balachandar answer. if you want to hide p tag initially then use display:none for p tag
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle(function(){
var btn_text = $("#"+SelectedID).val();
if(btn_text == "View More"){
$("#"+SelectedID).val("Hide");
}else{
$("#"+SelectedID).val("View More")
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn btn-info" id="myID" onclick="Clicked(this)" value="View More" /> <p style="display:none"> Some Text you want to in future </p>
Try this below code
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle();
};
Hope this will help you.
You can select the element by its id and find the p element inside:
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).find("p").toggle();
};
Or just use this:
function Clicked(e)
{
$(this).find("p").toggle();
};
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).toggle();
};
You can use:
function Clicked(d)
{
var SelectedID = d.id;
$("#" + SelectedID).toggle();
};
This function picks all p inside td of your table and hides all of them, then it shows only the one with the same ID as the button.
function Clicked(e) {
var SelectedID = e.id;
$("td p").hide();
$("#" + SelectedID).show();
};

Renaming form fields added or deleted dynamically

I'm looking for help to rename the name attributes of some fields created dynamically.
Now, my code assigns new values to the added fields (it increments according to the length of the div) but the problem appears when I delete a field, I don't know how to rename the remaining according to the number of fields deleted.
jQuery:
$(document).ready(function () {
$("#add").click(function () {
var intId = $("#reglas div").length;
var fieldWrapper = $('<div></div>', {
class: 'fieldwrapper',
id: 'field' + intId
});
var fPath = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fTTL = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function () {
$(this).parent().remove();
});
fieldWrapper.append(fPath);
fieldWrapper.append(fTTL);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function () {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
HERE'S MY FULL CODE: http://jsfiddle.net/34rYv/131/
You will want an incrementor. Check out this updated fiddle.
Here is the beginning of the code:
$(document).ready(function() {
var myIncr = 0;
$("#add").click(function() {
myIncr++;
var intId = myIncr;
You can add a class or id to each input field, and then depending on that class or id add the name as
<input type="text" class="something" />
Use this jQuery:
var classval = $('input[type=text]').attr('class'); // get class..
// now add the name as
$(this).attr('name', classval);
You can have as many inputs, they will be added the name depending on their class or id!
So even if the input fields are deleted, you will still have the class attributes in the control!

Javascript append/remove elements

I have one question. Is possible delete <span> element added with javascript append?
When i try remove added span then nothing happens.
Like this:
<script type="text/javascript">
$(document).ready(function(){
$('#SelectBoxData span').click(function(){
var StatusID = this.id;
var StatusIDSplit = StatusID.split("_");
var StatusText = $('#SelectBoxData #' + StatusID).text();
$("#SelectBox").append('<span id=' + StatusID + '>' + StatusText + '</span>');
$("#SelectBoxData #" + StatusID).remove();
InputValue = $("#StatusID").val();
if(InputValue == ""){
$("#StatusID").val(StatusIDSplit[1]);
}
else{
$("#StatusID").val($("#StatusID").val() + ',' + StatusIDSplit[1]);
}
});
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
});
</script>
<div id="SelectBoxBG">
<div id="SelectBox"><div class="SelectBoxBtn"></div></div>
<div id="SelectBoxData">
<span id="StatusData_1">Admin</span>
<span id="StatusData_2">Editor</span>
<span id="StatusData_4">Test 1</span>
<span id="StatusData_6">Test 2</span>
</div>
<input type="hidden" id="StatusID" />
</div>
Please help me.
Thanks.
Yes, you can delete them. However, you can't add click event handlers to them before they exist. This code:
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
will only add a click event handler to <span> elements inside of #SelectBox at the time the code is run (so, based on your provided HTML, zero elements). If you want the event handler to react to dynamically added elements then you need to use a technique called event delegation, using the .on() function:
$('#SelectBox').on('click', 'span', function() {
$(this).remove(); // equivalent to the code you had before
});

Categories

Resources