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
});
Related
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());
});
I am trying to figure out why I am unable to remove multiple neighboring elements on a successful ajax DELETE. When I had $(".file-preview").filter("a[href='" + fileLink + "']").remove(); by itself in the code below, I was able to remove the first link and when I add $(".remove-file").data("file-link", fileLink).remove(); after it, it breaks the first .remove() statement and removes all of the present .remove-file disregarding the value being passed to the data-file-link attribute in the link.
1) Why would the first remove be broken by this second remove?
2) Is there a better approach to what I'm trying to achieve which is to remove both neighboring elements on the click of .remove-file?
Here is an example of what the HTML looks like:
<div class="file-section>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
</div>
jQuery:
$(document).on('click', '.remove-file', function(){
console.log('Delete Triggered');
var fileLink = $(this).data('file-link');
function pathExtract(url){
var fullUrl = url;
var delimiter = '/';
var start = 3;
var tokens = fullUrl.split(delimiter).slice(start);
var path = tokens.join(delimiter);
return path;
}
$.ajax({
url: '/app/sign?' + $.param({"file": pathExtract(fileLink)}),
type: 'DELETE',
success: function(){
console.log('This is the file link ' + fileLink);
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
$(".remove-file").data("file-link", fileLink).remove();
},
error: function(error){
console.log('error ' + JSON.stringify(error));
}
});
});
.data("file-link", fileLink) isn't a filter, it sets the data of the elements selected. It simply returns the same collection it was called on, so when you call .remove() on the result it removes all the elements with the remove-file class.
If you want to remove just the elements with that data value, use .filter():
$(".remove-file").filter(function() {
return $(this).data("file-link") == fileLink;
}).remove();
This code:
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
doesn't work because the a element is inside the .file-preview DIV, but .filter() tests if the element itself matches the filter. You should write:
$(".file-preview:has(a[href='" + fileLink + "'])").remove();
to test the contents.
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.
I basically have a field element with name="one".As soon as I fill the field,the value should be appended to an href <a name="number" href="example.php" </a> .
It should append it in the format href="example.php?number=one" after i fill the field.Is this possible?Im new to jquery.
I have this for getting the values in the jquery
var num = $("[name='number']").val();
but the rest,appending things,im not sure how to do that.Any help?
Try
var $a = $('a[name="number"]');
//store the original value so that we can handler multiple changes
$a.data('href', $a.attr('href'))
$("#one").change(function () {
$a.attr('href', $a.data('href') + '?number=' + this.value)
});
Demo: Fiddle
Note: This solution does not support handling values from multiple input elements
With this:
var $a = $("a[name=number]"),
href = $a.attr("href");
$a.attr("href", href.split('?')[0] + "?number=" + num);
Cheers
DEMO : http://jsfiddle.net/ETsA8/5/
Html :
<a name="number" href="example.php">ss </a>
<input id="one" type="text" >
Js:
$( document ).ready(function() {
var link = $("[name='number']").attr("href");
$("#one").change(function(){
var a_href = $("#one").val();
$("[name='number']").attr("href", link+'?number='+a_href);
});
});
$('a[name="number"]').attr(href(function(i, oldhref) {
return oldhref + '?number=' + value;
});
I'm trying to devise a method of when adding a simple div element with a class and some data-* in it, it will replace it or add into it some other elements. This method should not be called manually, but automatically by some kind of .live() jQuery method, a custom event or some kind like $('body').bind('create.custom'), etc.
I need it this way since I wouldn't know in advance what elements will be created since they will be served through ajax like single empty div's or p's .
<!DOCTYPE html>
<html>
<head>
<title >on create</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
$("div.fancyInput").each(function(index,element){
var $div = $(this);
var dataId = $div.attr("data-input-id");
var inputId = '';
var labelId = '';
if(!!dataId){
inputId = 'id="' + dataId + '"';
labelId = 'id="' + dataId + 'Label"';
} // if
var dataValue = $div.attr();
$(
'<p class="fancyInput" >' +
' <label ' + labelId + ' for="' + inputId + '" >A fancy input</label>' +
' <input ' + inputId + ' name="' + inputId + '" value="A fancy input" />' +
'</p>'
).appendTo($div);
}); // .each()
}); // jQuery()
</script>
<script type="text/javascript" >
jQuery(function($){
var counter = 2;
var $form = $('#form');
$('#add').click(function(event){
$('<div class="fancyInput" data-input-id="fancyInput' + counter + '" ></div>').appendTo($form);
counter++;
}); // .click
}); // jQuery()
</script>
</head>
<body>
<a id="add" href="#" > add another one </a>
<form id="form" action="#" >
<p class="normalInput" >
<label id="normalInputLabel" for="normalInput" >A normal input</label>
<input id="normalInput" name="normalInput" value="A normal input" />
</p>
<div class="fancyInput" ></div>
</form>
</body>
</html>
Update:
I checked liveQuery beforehand, it's that kind of functionality that I need, but with the ability to modify DOM elements while the event callback is executed. So it's not just that I need events attached, but the ability to modify the DOM upon element creation. For example: whenever a new is created, it should be filled in (even better if replaced) with the p, label and input tags
You could use a DOM Level 3 Event, like DOMNodeInserted. This could look like:
$(document).bind('DOMNodeInserted', function(event) {
// A new node was inserted into the DOM
// event.target is a reference to the newly inserted node
});
As an alternative, you might checkout the .liveQueryhelp jQuery plugin.
update
In referrence to your comment, have a look at http://www.quirksmode.org/dom/events/index.html, only browser which do not support it are the Internet Explorers of this this world (I guess IE9 does at least).
I can't say much about the performance, but it should perform fairly well.