jQuery appending li to ul unclickable - javascript

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

Related

having trouble deleting specific html element with javascript

I'm having trouble deleting the specific element that the delete button is for, instead it deletes the last in the array, or the first with my previous code, any help is greatly appreciated. Vanilla js.
Codepen: https://codepen.io/Adrw4/pen/LzvjLj
idNum--;
console.log(idNum);
console.log(array);
var node = document.getElementById(idNum);
node.parentNode.removeChild(node);
Instead of relying on the ID of the elements, just pass in the event to the deleteTodoItem function on click event. Based on the knowledge of the DOM, you can find out the related li element and delete it.
function deleteTodoItem(event) {
var node = event.target.parentNode;
node.parentNode.removeChild(node);
};
Here's the updated codepen:
https://codepen.io/Nisargshah02/pen/OxGjOr?editors=1010

jQuery - capturing LAST dynamic element

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.

Deleting <li> issue

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/

Using remove as opposite of append not working

Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});

jqTransform Update Select Options

I'm dynamically altering a select list's options. I am using the jqTransform plugin. It won't update itself automatically, which I didn't expect it would, but I can find a method for updating the display. I can't even find a method for removing it completely.
What I'd like is to find a method such as formelement.jqTransformUpdate() that will fix this. Any ideas?
I know it's an old question, but maybe it helps someone. I couldn't find the answer, so I looked into jqtransform.js code.
Just comment this line:
if($select.hasClass('jqTransformHidden')) {return;}
And then, after "onchange" event run:
$('#container select').jqTransSelect();
function selectRating(rating) {
$("#ratingModal .jqTransformSelectWrapper ul li a").each(function() {
if (parseInt($(this).attr("index")) == rating - 1) {
$(this).click();
}
});
}
A JS function I used in my own application to select specific option with the given rating.
I think you can modify it to meet your needs.
The idea is to use a.click event handler to select specific option in the transformed select list.
hi please try the following to selectively reapply styling to newly created or
select box returned from the ajax request
$('#container select').jqTransSelect();
regarding this:
That adds another drop-down to the page every time I call it now
When you comment this line:
if($select.hasClass('jqTransformHidden')) {return;}
add this just below:
if($select.hasClass('jqTransformHidden')) $select.parent().removeClass();
it's not a very elegant solution, but it worked in my case, the new select is still nested inside child and so on but it's working fine.
It could be better, try to add new method in jqtransform.js:
$.fn.jqTransSelectRefresh = function(){
return this.each(function(index){
var $select = $(this);
var i=$select.parent().find('div,ul').remove().css('zIndex');
$select.unwrap().removeClass('jqTransformHidden').jqTransSelect();
$select.parent().css('zIndex', i);
});
}
after that, just call it each time you need to refresh the dropdown:
$('#my_select').jqTransSelectRefresh();

Categories

Resources