czomberzdaniela
czomberzdaniela

Reputation: 71

Dynamically remove a dynamically added input (type=file)

I have a form where user can add files to be uploaded. Change event on that input adds new input the same type and so on. But the new inputs have to have "X" character with click event attached to it to be able to remove the input field and the X chracter.

The form:

  <form id="upload_form">
     <div class="p_file">
        <p class="icon">X</p>
        <input type="file" name="userfile1" size="40"  class="required"  />
     </div>
  </form>

and the JavaScript:

   $('#upload_form input[type="file"]').change(function(){
       addUploadField($(this));
   });  

   function addUploadField($field)
   {
       $current_count = $('#upload_form input[type="file"]').length
       $next_count = $current_count + 1;
       $field.parent('p').after('
            <div class="p_file" >
                <p class="icon">X</p>
                <input type="file" name="userfile'+$next_count+'" size="40" />
            </div>
        ');
        $field.unbind('change');
        $nextField = $('#upload_form input[type="file"]').last(); 
        $nextField.bind('change',function(){
        addUploadField($(this));
     });

     $("#upload_form .icon").on('click',function(){
         removeUploadField($field);
     });
   }

 function removeUploadField($field)
 {
     $field.parent('p').remove();
 }

The code above remove all the fields after the clicked 'X' character. What I want to do is to remove only the next input field.

I tried to prepare this example in jsFiddle, but I can't make this work. Anyhow maybe this would help.

Upvotes: 1

Views: 1510

Answers (1)

Anjith K P
Anjith K P

Reputation: 2158

Putting "div" tag inside "p" tag is the main problem


Remove is corrected in this code

Note: In your html code "div" is is added inside "p" tag, this is invalid practice

HTML:

<form id="upload_form">
    <div class="p_file">
        <div class="icon">X</div>
        <input type="file" name="userfile1" size="40"  class="required"  />
    </div>
</form>

Script:

$('body')
    .delegate('#upload_form input[type="file"]', 'change', inputChanged)
    .delegate('#upload_form .icon', 'click', removeField);

function inputChanged() {

    $current_count = $('#upload_form input[type="file"]').length;
    $next_count = $current_count + 1;
    $(this).closest('.p_file').after(
            '<div class="p_file" ><div class="icon">X</div>' +
            '<input type="file" name="userfile'
            + $next_count + '" size="40" /></div>');
}

function removeField(){
    $(this).closest('.p_file').remove();
    return false;
}

Link: http://jsfiddle.net/cBrQX/2/

Upvotes: 2

Related Questions