I'm building a recipe saving application where I have a form that looks like this http://jsfiddle.net/LHPbh/.
As you can see, I have a set of form elements contained in an <li>. You can click Add Ingredient and have more li's added to the field.
My problem is:
The first li is the only one that deletes. If you click Add Ingredient, and then try and delete that one, nothing works?
Is there a way to not have the first li have a delete by it, but all subsequent li's have a delete link on the side? (Just because there should always be at least one ingredient?)
When you call clone(), it isn't duplicating the events. You need to call clone(true) in order for it to do this, as explained in the documentation.
You did not put an event listener on the cloned elements. Also, you should not give the "delete"-link its own id, as those need to be unique.
To make the first ingredient have no delete button, just don't include one in your markup but only dynamically create and append them to the cloned elements:
var deleteButton = $("<a class='float-left'>Delete</a>").click(deleteThis);
$('ul#listadd > li:first')
.clone()
.attr('name', 'ingredient' + newNum)
.append(deleteButton)
.appendTo('ul#listadd');
function deleteThis() {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
}
Demo at jsfiddle.net
http://jsfiddle.net/LHPbh/2/
$('.deleteThis').live("click", function () {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
});
It is answer to the 1. point. The problem was, that the eventhandler binding did not happen in newly created elements, because this code runs only on the load of the page. This can be solved by using .live(). And an other problem was, that id-s must be unique. So instead id, here you can use class .deleteThis.
http://jsfiddle.net/LHPbh/19/
This has added answer to the 2. point:
if ($("#listadd li").length == 1) {
return;
}
If the list only contains 1 li element the rest of the callback will not run.
You are adding items that are added to the DOM dynamically, thus jQuery can't access them :)
In this case you can use the following code:
$(document).on('click', '.selector', function(e) {
//code here
});
Secondly, you were loading a quite old version of jQuery.
Thirdly, you were trying to select an element with an ID that already existed, and ID's can only exist one time. I've changed it to a class in the updated example.
Lastly, you were defining the class of the link twice like this:
<a class='float-left' id="deletethis" href='#' class="deletethis">Delete</a>
That also gave a problem, so I changed it to correct markup like this:
<a class='float-left deletethis' href='#'>Delete</a>
Good luck :) I've updated your jsFiddle here:
http://jsfiddle.net/q4pf6/
Related
I am using .map to get an array of element IDs (this is named 'ids') that have a 'default-highlight' class. After removing that class on mouseenter, I want to return that class to those specific id's (basically, leave it how I found it).
Two things are causing me trouble right now:
When I dynamically add data-ids to the td elements and then use those data-ids to create the array of 'ids' my mouseenter stops adding the 'HIGHLIGHT' class (NO idea why this is happening)
On mouseleave I can't loop through the 'ids' and return the 'default-highlight' class to the elements they originally were on
I figure I should be using something like this, but it obviously isn't working:
$.each(ids, function() {
$(this).addClass('default-highlight');
});
I have tried a number of things, but keep coming up short. I am attaching a link to a codepen.io where I use data-ids that are being dynamically added to the table (this one the mouseenter doesn't work) and a codepen one where I am using regular IDs for the default highlight and everything appears to work like it is supposed to be (It isn't, since I want to be using the dynamically generated data-ids and then the subsequently produced array to reapply those classes).
Both of these codepens have a gif at top showing how the interaction should work.
If anything is unclear, please let me know. Thanks for reading!
You need to add # before id selector
$.each(ids, function() {
$('#'+this).addClass('default-highlight');
});
or you can use common selector by the help of map() and join()
$(ids.map(function(i, v) {
return '#' + v;
}).join()).addClass('default-highlight');
or you can add # when getting the id's and then you just need to join them
var ids = $('.default-highlight').map(function(i) {
return '#'+$(this).data('id');
}).get();
...
...
...
$(ids.join()).addClass('default-highlight');
It seems like storing the IDs and using those is overkill when you can store a reference to the jQuery element directly:
$highlightCells = $('.default-highlight').removeClass('default-highlight')
And later give the class back:
$highlightCells.addClass('default-highlight')
Here's a codepen fork: http://codepen.io/anon/pen/ZbOvZR?editors=101
Use this way:
$.each(ids, function() {
$("#" + this).addClass('default-highlight');
});
I am adding new forms to my DOM dynamically, but the thing is that my code only captures first dynamically added element and not the last one.
This is my code. The screenshot below also explains everything.
Screenshot:
$('#buildyourform').on('click', '.remove_dyn_summary', function() {
var $txtarea = $(this).closest('b').find('.new_dyn_summary').val(); // this part is wrong
alert($txtarea)
});
P.S. my business logic doesnt allow me to add incrementing numbers in classes or something.
.last() or :last didnt work for me I guess because elements were added dynamically.
I am probably missing something very simple..
Use event delegation.
$(document).on('click','#buildyourform:last p.remove_dyn_summary', function() {
var $txtarea = $(this).parent().prev().prev().children('textarea.new_dyn_summary').val();
alert($txtarea);
});
Try the above.
I have many li(list) items which are generated by a loop thanks to java servlets, now
I want to change the class of the current li(list) which is selected
$('li.doBlokkeer').click(function(e) {
$('.doBlokkeer').addClass('doDEBlokkeer').removeClass('doBlokkeer');
});
so if a current li is selected its class need to be changed (it needs to have doDEBlokkeer).
The above code works.. but it changes ALL my li items... so guys do you know how to change the class of the current item $(this) ? I have no jquery skill, pls help me out. Thanks!!
You need to use $(this) instead of $('.doBlokkeer') in the click event handler. As $('.doBlokkeer') will return all the elements having class doBlokkeer where as $(this) represents the jQuery object that is source of the event.
Live Demo
$('li.doBlokkeer').click(function(e) {
$(this).addClass('doDEBlokkeer').removeClass('doBlokkeer');
});
You can also try using toggleClass to switch between two classes.
Live Demmo
$('li.doBlokkeer').click(function(e) {
$(this).toggleClass('doDEBlokkeer');
});
i have the following code that adds data to unordered lists. The troublesome code is as follows:
$('li:not(:first-child)').click(function() {
var clickedLi = this;
$(this).parent().prepend(clickedLi);
var selectedLi = $(this).text();
alert(selectedLi);
$(this).parent().parent().nextAll().children('ul').children().replaceWith('<li>Please select</li>');
//ajax call
var returnedData = "<li>Dataset1</li><li>Dataset2</li><li>Dataset3</li>";
//populate next with returned data
$(this).parent().parent().next().children('ul').append(returnedData);
});
If you click on one of the options in the first ul, data gets added to the second ul. However, the list items under this ul are not clickable, and I need them to be so, so that 'chain' can be continued.
Where is the bug? Any help would be much appreciated. Thanks in advance.
Try with: (if you use jQuery greater than 1.6.8. )
$(document).on('click','li:not(:first-child)',function() {
http://api.jquery.com/on/
I can suppose, judging by your code, that you expect the freshly added li to inherit the behaviour you append to the existing ones. Unfortunately it cannot work with the code written that way.
You need to attach the click event in an "observable" way so newly added elements to the dom will get the event handler attached.
To do this, you must use the .on method. You can check its reference here
I'm new to javascript and JQuery, and I'm working in a small project with JSP.
I create a grid dynamically with JSP and I added some buttons wich class is "select" and in the alt attribute I set the current row index. That works perfectly, I'm trying to set the onclick dynamically. This is my code
$('.select').click(function (){
alert($('.select').attr('alt'));
}
I want to each button to show its own index, but that code shows just the first index in each button. I've searched how to do it, but nothing comes out.
Is there a chance to do what I want?
change this line as:
alert($(this).attr('alt'));
When jQuery calls your event handler it sets this to be the DOM element in question, so try this:
$('.select').click(function (){
alert($(this).attr('alt'));
});
If you need to access DOM element properties you can then get them directly, e.g.:
alert( this.id );
this.value = "test";
If you need to use jQuery methods on the element you need to pass it to the jQuery function first, e.g.:
$(this).hide();
$(this).css("color","red").slideDown();
$('.select').click(function (){
alert($(this).attr('alt'));
});
Change
alert($('.select').attr('alt'));
by
alert($(this).attr('alt'));
Now you select the attr alt of the button lauch the event.
Not sure if that's what you're looking for but...
$('.select').click(function() {
$('.select').each(function() {
$(this).attr('value', $(this).attr('alt'));
});
});
This'll have every button "show" the value stored within their alt attribute when you click one button.
By the way, if you're using 1 button per row, you'd probably better go with index().