2012-05-25 51 views
0

我试图添加和删除一个输入框,当一个框被勾选。 但是,我似乎有几个问题。 Im不确定的一个细节是我如何将$ this(div)与其他属性链接起来。添加和删除一个输入框

HTML:

<form> 
    Lifetime Secs <input id="sec" type="checkbox" name="sec" value="sec" /> <br /> 
    Lifetime KBytes <input id="kb" type="checkbox" name="kb" value="kb" /> 
</form> 

的JavaScript:

$("#input1, #input2").click(function() { 
    if ($("this:checked").length) { 
     $(this).after('<input type="text" name="input" id="inputbox" />'); 
    } else { 
     $('this input').remove(); 
    } 
}); 

的jsfiddle:http://jsfiddle.net/felix001/eA32C/22/

感谢,

+1

最好将代码粘贴到问题中。 – VisioN

回答

1

情侣修复的问题..见下文,完成这

$(function() { 
    $('input:checkbox').change(function() {   
     if ($(this).is(':checked')) { 
      $(this).after('<input type="text" name="input" id="inputbox" />'); 
     } else { 
      $(this).next('input').remove(); 
     } 
    }); 
}); 

DEMO

+0

现货。感谢您的帮助... – felix001

0
$(function() { 
    $('input:checkbox').on('change', function() { 
    if (this.checked) { 
     $(this).after('<input type="text" name="input" id="inputbox" />'); 
    } else { 
     $(this).next('input').remove(); 
    } 
    }); 
}); 
0
$("#sec,#kb").click(function() { 
    $this = $(this); 

if ($this.attr('checked')) { 

    $this.after('<input type="text" name="input" id="inputbox" />'); 

} else { 

    $('#inputbox').remove(); 

} 
}); 

http://jsfiddle.net/eA32C/39/

+0

是否有必要参考$(this)? – thecodeparadox

+0

不,只是不需要在那两次调用jq ...通常为我的jq对象做这件事 –