jQuery using parent method to add new row
Here I have a html code where I have input textbox planted in a row. How can I use the '+' button in the same table while using ONLY parent()
function to create a new row within the table that contains 开发者_开发百科another input textbox?
I have some sample jQuery code here but they don't really work:
$(".plus").live("click", function(){
var parent = $(this).parent().parent().parent(".iteration");
parent.after('<table width="100%" border="0" bordercolor="#000000"><tr><td colspan="2"><label><input type="text" value="Create a task for this iteration" size="75%" height="25px"/></label></td></tr></table>');
var nbinput = parent.find("input[type='text']").length;
if(nbinput == 5)
parent.find(".plus").attr("disabled","disabled");
else if(nbinput == 2)
parent.find(".moins").attr("disabled","");
});
$(".moins").live("click", function(){
var parent = $(this).parent().parent().parent(".iteration");
parent.children("input").last().remove();
var nbinput = parent.find("input[type='text']").length;
if(nbinput == 4)
parent.find(".plus").attr("disabled","");
else if(nbinput == 1)
parent.find(".moins").attr("disabled","disabled");
});
Well, some simplification will go a long way:
var parent, attribute_toggle;
attribute_toggle = function (nbinput, parent) {
switch(nbinput) {
case 5:
parent.find('.plus').attr('disabled', 'disabled');
case 4:
parent.find('.plus').removeAttr('disabled');
case 2:
parent.find('.moins').removeAttr('disabled');
case 1:
parent.find('.moins').attr('disabled', 'disabled');
}
};
$('.plus').live('click', function() {
parent = $(this).parents('.iteration:first');
parent.after('... removed for brevity ...');
attribute_toggle(parent.find('input:text').length, parent);
});
$('.moins').live('click', function() {
parent = $(this).parents('.iteration:first');
parent.children('input:last').remove();
attribute_toggle(parent.find('input:text').length, parent);
});
Updated to be easier to read, and merged the switch into a function.
There, now that it is a bit more legible, explain what happens when you try to run this code, and contrast that with what you would like to happen.
I think it's your series of parent()
. It looks like you're not factoring in elements such as the td and tr. just try var parent = $('.iteration')
I don't know the exact expected outcome for the UI so i can't say more beyond that.
精彩评论