I created a simple "endless" form with input fields. Each time the empty input is focused, it creates a new one, and when the empty input field is eroded, the field is deleted.
See an example here.
I use the following code to make this all happen:
var $input = $('<div/>').html( $('<input/>').addClass('value') ); $('form').append( $input.clone() ); $('form').on( 'focus', 'input.value', function(e) { // Add new input if the focused one is empty if(!$.trim(this.value).length) { $('form').append( $input.clone() ); } }).on( 'blur', 'input.value', function(e) { var $this = $(this); if( !$.trim(this.value).length ) { console.log('REMOVING INPUT'); $this.parent().remove(); } else { $this.attr('name', 'item-'+$this.val()); } });
However, the problem is that in Chrome, the blur
event is fired twice when I switch to another application ( β tab ). This gives an error because it is not possible to remove the node since it is already gone:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
Firefox is working fine.
So why does the blur
event fire twice and how can I prevent this?
EDIT - tried the answer in this question , but no luck. Still getting an error message in Chrome, what am I doing wrong?
See updated script
Is there a way to check if an item still exists? Since the second time the blur
fires, the node is removed. $(this).length
is still nonzero.
source share