Reputation: 2576
I am generating div
boxes using script :
$('.FieldContainer a.add').click(function(){
$('.FieldContainer').append(
'<div class="OrderingField">'+
'<div class="LeftFloat">'+
'Item'+
'</div>'+
'<div class="RightFloat Commands">'+
'<button value="up" >Up</button>'+
'<button value="down" >Down</button>'+
'</div>'+
'</div>'
);
});
Here is my jsfiddle http://jsfiddle.net/maziar/P2XDc/ link
Up-Down button are working on preloaded div
elements but div element which are generating using above script are not moving up-down using that button .
How to correct this?
Edit:
Working Example: http://jsfiddle.net/P2XDc/182/
Upvotes: 0
Views: 1520
Reputation: 2759
$('.FieldContainer a.add').click(function(){
$('.FieldContainer').append(
'<div class="OrderingField">'+
'<div class="LeftFloat">'+
'Item'+
'</div>'+
'<div class="RightFloat Commands">'+
'<button value="up" >Up</button>'+
'<button value="down" >Down</button>'+
'</div>'+
'</div>');
$(".FieldContainer").sortable("destroy");
$(".FieldContainer").sortable({
items: ".OrderingField",
distance: 10
});
});
Upvotes: 0
Reputation: 3514
You need to apply the .click()
you peform on startup also on newly created divs, as the jQuery selector is currently only executed on startup. You might perform this like the following:
$('.FieldContainer a.add').click(function(){
$('.FieldContainer').append(
'<div class="OrderingField">'+
'<div class="LeftFloat">'+
'Item'+
'</div>'+
'<div class="RightFloat Commands">'+
'<button value="up" >Up</button>'+
'<button value="down" >Down</button>'+
'</div>'+
'</div>'
).find('button').click(function() {
var btn = $(this);
var val = btn.val();
if (val == 'up')
moveUp(btn.parents('.OrderingField'));
else
moveDown(btn.parents('.OrderingField'));
});
});
UPDATE: as your click()
needs to be applied to buttons instead, I inserted the find('button')
selector. I updated your fiddle.
Upvotes: 2
Reputation: 794
Add a global handler for all buttons:
$(".FieldContainer").on("click", "button", function(){console.log("works")})
Upvotes: 1
Reputation: 5742
You are adding the elements after the events have already been bound. If you want to have the same events on dynamically added elements, you will need to bind the click to those buttons after they are added
Upvotes: 0