I'm trying to append and remove element in the inputfield.
I can simply append them and it works fine but I don't know hwy it doesn't get deleted/removed when I needed it to!
To explain this issue I have created this fiddle: http://jsfiddle.net/hrL3gn1g/2/
if you click on the images, it will append the element in the div Slevel as well as the inputfield.
If you click on the elements inside the Div, it should delete/remove the element or string from inside the inputfield but it doesn't
could someone please advise on this issue?
You can try this:
$(document).on('click', '.pricetag',function(){
var names = $(this).attr('data-name');
var price = $(this).attr('data-price');
// Create the value you want to remove
var html = '<span data-price="'+price+'" data-name="'+names+'" class="pricetag">'+names+'</span>';
// Replace that value with empty string
var newValue = $('#Finalized').val().replace(html,'')
// Insert new value
$("#Finalized").val(newValue);
});
as i see , you try to remove the words(orange,apple etc) by using $(<input>).remove(<span>), but you cant do this in that way.instead of this , i remove the selected <span> element.
i changed a little the click listener function to this one:
//when the user click on a word
$(document).on('click', '.pricetag',function(){
//this is the <span> element that the user clicked to delete
$(this).remove();
});
i changed the jsfiddle : http://jsfiddle.net/tornado1979/hrL3gn1g/3/
hope helps,good luck.
Related
Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.
Thanks!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
$('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});
$('#approve').on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:
$('#yourContainer').on('click', '#approve', function(){
//your code here..
});
Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should
bind .on() with $(document) selector. This will always contain your dynamically added elements.
$(document).on( eventName, selector, function(){} );
$(document).on('click','#approve',function(){
//your code here
});
I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:
// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');
// This won't work...
$("#mynewthing")...
// But this will...
$(document.getElementById("mynewthing"))...
This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.
Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var $button = $('<button style ="button" id="approve">Approve</button>');
$button.on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
$('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});
Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.
A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var id = snapshot.name();
var $button = $('<button style="button">Approve</button>');
$button.on("click", function(){
// use parent.closest(...) in place of an ID here!
var text = $(this).parent().closest('textarea').val();
postsRef.push({'text':text});
$(this).parent().remove();
});
/* just an example of how to use a data-* tag; I could now refer to this element using:
$('#feed').find('[data-record="'+id+'"]') if I needed to find it */
$('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});
I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.
$("#button").click(function(e){
$(".parentContainer").find(".dynamically-child-element").html("Hello world");
});
Or
$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event
So this is my demo
I currently have a table and in 1 column a Delete link, if the user clicks this link it fires an onClick which basically flags that item to be deleted and hide the TR.
It works fine, but I am just wondering if there is a better way .....
$(document).on('click', '.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
var target = $(e.target);
if (!target.is('td')) {return;}
var h = this.innerHTML;
var newH = h.replace("CsUpdated", "CsDeleted");
newH = newH.replace("CsAdded", "CsDeleted");
this.innerHTML = newH;
//We clicked on a TD so get the row TR.
var theRow = $(this).closest('tr');
theRow.hide();
});
I just think there must be a better way than the string manipulation I am doing with the replace? Is there?
I've tried these but with no luck...
$(this).attr('value', 'CsDeleted');
$(target).attr('value', 'CsDeleted');
$(this).val('CsDeleted');
$(target).val('CsDeleted');
Thanks
td has no value use .text() or .html()
td doesnt have a value attribute.
Use
$("td").html() // to fetch html
$("td").html("<span> Hello World </span>") // to set html
$("td").text() // to fetch plain text
$("td").text("Hello World") // to set plain text
You could use any of the following to set the cell contents
.html() or .text() or .prependor .append and more
However .val() only works on inputs that have the value="...." attribute. If you want to prop the Cell with some data use .data("key","value") which can be accessed at any point by calling .data("key");
Try this one,
$(function(){
$('.delete').click(function(){
$(this).closest('tr').remove();
});
});
You may use custom data-- attributes on any html element ( see this MDN article and the reference ). These are accessible through jquery's attr method and have no influence on rendering.
Code PoC:
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this)
.removeAttr('data-CsUpdated')
.removeAttr('data-CsAdded')
.attr('CsDeleted', '1')
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
In case the values given in your code are mutually exclusive, this simplifies to
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this).attr('Cs', 'Deleted');
// attr 'Cs' contained 'Added' or 'Updated'
// This scheme requires modifications at other places in your original code !
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
Update
As the OP actually wants to modify the value of a child input element, the handler reduces to:
$(document).on('click', 'td.deleteCell', function (e) {
$('input', $(this)).val('CsDeleted');
// more specific selector may be needed depending on possible cell contents
$(this).closest('tr').hide();
});
I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});
So I need to grab content from a specific class and put it in a div, which I use append for...my issue is that append removes the item I append, and I need it to stay there, Here is my code:
$(document).ready(function(){
var $content = $('#popupcontent');
var $window = $('#popupwindow');
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a);
$window.fadeIn(300);
});
$('.close').click(function(){
//alert('running');
var a = $content.contents('span');
$window.fadeOut(300);
$('#popupcontent span').remove();
});
});
So how can I get the content, when clicked, from each .open span to the #popupcontents id without removing it from the .open class?
To show you what I mean: JSFIDDLE
NOTE: the second time you click a link, it wont append any content because that content has been removed from that class, which is not what I want
NOTE2: I cannot simply just append instead of remove in the $('.close').click function because I cannot detect which instance of the .open class the content came from.
You need to clone the element and append the clone:
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a.clone());
$window.fadeIn(300);
});
Demo
Below is html part
<li class="main_menu catagory_li" id="cat4">
<p class="ahead"><span class="heading">Item 4</span>
<span class="fright remove">close</span></p>
</li>
when i click close i copy the LI using below code,
$('.remove').live('click',function(){
var closed_elem_id = $(this).parent().parent().attr('id');
s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('li#'+closed_elem_id).remove();
console.log(s);
});
This one removes the LI in particular place and get the copy and store it in variable s.
My requirement is to add class called no-display in cloned copy like <span class="fright remove no-display">close</span> . I tried this many ways but it fails.
Kindly advice on this
NOTE : updated my question
A little optimized: http://jsfiddle.net/hKUd6/
Something like this:
$('.remove').live('click',function(){
var pLi = $(this).closest('li');
s = $('<div>').append(pLi.clone().addClass('no-display')).html();
pLi.remove();
console.log(s);
});
This whole thing is very sloppy. You don't need to use as much code as you have to accomplish the simple task you're attempting.
Try something like this:
$("li").on("click", ".remove", function(){
var $this = $(this),
liCont = $this.closest("p"),
parentLi = $this.closest("li");
liCont
.clone()
.wrap(
$("<div>").addClass("no-display")
)
.appendTo("body");
parentLi.remove();
});
What we do here is capture the click event on any .remove elements. We select the parent p (which we later clone to wrap with a div) as well as the parent li. We clone the p element (including its contents), wrap it with a div element (which we create using DOM scripting and add the class), and append the finished product to the body (you can change that if needed). We then remove the original li.
Try with this code, it should work:
$('.remove').live('click',function(){
var closed_elem = $(this).closest("li"); //get the li to be closed/removed
var clonedElem = closed_elem.clone().find("span.remove").addClass("no-display"); //clone the original li and add the no-display class to the span having remove class
closed_elem.remove(); //remove the original li
console.log(clonedElem);
});
Please check below lines of code.
first of all you need to get current class name using jquery:
$('li #cat4').find('span').each(function(){
var classname = $(this).attr('class');
$(this).addClass(classname+' no-display');
});
This is not a complete code of your task, but its just a code by which you can get a current class and then add more required string to it and set new class.
Thanks.