Qarchli Ismail
Qarchli Ismail

Reputation: 157

I would like to clone two input fields using JQuery

I am trying to create a form where the user might want to add two input fields dynamically, and this form is linked to the validate JQuery Plugin.

$('.addnote').on("click",function(){
    countnotes++;
    var newnote = $(".notes:first").clone();
    newnote.find('input:file').val("");
    newnote.find('input:text').val("");
    var oldindexinput = countnotes-2;
    var newindexinput = countnotes-1;
    var attachement = newnote.find('#Justificatif'+oldindexinput+'Attachment');

    attachement.attr('id','Justificatif'+newindexinput+'Attachment');
    attachement.attr('name','data[Justificatif]['+newindexinput+'][attachment]');
    var motif = newnote.find('#Justificatif'+oldindexinput+'Motif');

    motif.attr('id','Justificatif'+newindexinput+'Motif');
    motif.attr('name','data[Justificatif]['+newindexinput+'][motif]');
    newnote.find('input:text[readonly]');
    var firstnoteid = $(".notes:first").attr('id');
    newnote.attr('id','notes'+countnotes);
    newnote.attr('style','');
    newnote.insertBefore('#'+firstnoteid).hide();
    newnote.slideDown();

});

Here is the Html code

<input name="data[Justificatif][0][attachment]" type="text" readonly placeholder="Feuille de support"  required>

<input name="data[Justificatif][0][motif]" placeholder="Motif de dépenses" class="input-medium" maxlength="255" type="text" id="Justificatif0Motif" required>

The problem with my code is that it clones the validation status as well with the new input fields, and I want to get rid of that.

Thank you

snapshot of the input fields cloned

Upvotes: 2

Views: 126

Answers (2)

DinoMyte
DinoMyte

Reputation: 8868

Typically, during jquery validation, class='required' is applied to the elements which are validation during form submit. Given, the elements you are cloning does have class='required' defined, you may simply remove it after cloning.

var newnote = $(".notes:first").clone();
newnote.removeClass('required');

Here's an example : http://jsfiddle.net/DinoMyte/TP768/268/

Upvotes: 2

J.R.
J.R.

Reputation: 6059

Some thoughts off the top of my head (based on a similar project I'm referencing):

  • Can you confirm that the id of the new input field is definitely unique. I see you calling "newnote.attr('id','notes'+countnotes);", but can you confirm the html is changed correctly?
  • If the id is unique, try unattaching and reattaching your validation engine. (In my code I kill everything and recreate my forms every time there's a change, then re-call jQuery($('form[name$="config_form"]')).validationEngine('attach');)

Upvotes: 0

Related Questions