Secondly what is the best way to remove a div instead of parent().parent().remove();
You can use closest():
$(this).closest('div').remove();
For the first part of your question you can define two different event handlers. The second one in order to delegate the remove click to the dynamically created divs under your main box.
In order to avoid duplicated IDs you can add a number to your id: the current div count:
$('#box').append('<div id="p' + count + '">......
Last point:
why declaring an event handler inside another is a threat?
In your case:
$(".delrow").on('click', function() {
Because, in this way you will attach more times the same event handler to each newly created divs. This means your code will call more times this event handler. In order to test this part you can add a console log message.
So, you have two main possibilities:
attach the event handler to the newly created div:
$("#box #p" + count).on('click', function() {
delegate the event to children divs under your box div
$("#box").on('click', '.delrow', function() {
The snippet:
$('#test').on('click', function() {
var count = $('#box div[id^=p]').length;
$('#box').append('<div id="p' + count + '"><input type="text" name="test[]"><a href="javascript:void(0);" class="delrow">Remove</a></div>');
$("#filled").val(count);
});
$("#box").on('click', '.delrow', function() {
var count = $('#box div[id^=p]').length;
$("#filled").val(count - 1);
$(this).closest('div').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test" href="javascript:void(0);">Add</a> <br />
<input type="number" id="filled">
<div id="box"></div>
[<>]toolbar button) to make your example runnable here, on site.divs withid="p1". So that's the first thing to fix. Also note that you're repeatedly adding the click hanlder to all pre-existing.delrowelements every time you add an element.