Marco Marco - 1 year ago 215
jQuery Question

jQuery - remove input field if input was deleted

I am adding input fields on keystroke, by using an example from the answer for this question. This is my example. I was trying in various ways to remove field if user deletes content from it, so that there are always fields that have some content and one last empty field for adding more, but I just can't find a solution.
This is the code:

$(document.body).on("input", ".external-media-input:last", function () {
var inputID = (parseInt($(this).attr('id')) + 1);
$(".input_fields_wrap").append('<div><input class="external-media-input" id="' + inputID + '" name="external_media[]" type="text"/></div>');

Answer Source

You can use on('blur') or .on('focusout')

.on('blur', ".external-media-input:not(:last)", function () {
    if(!$(this).val()) $(this).remove();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download