Skip to content

Instantly share code, notes, and snippets.

@FlaviuSim
Created February 9, 2012 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlaviuSim/1782822 to your computer and use it in GitHub Desktop.
Save FlaviuSim/1782822 to your computer and use it in GitHub Desktop.
jQuery('a.add-question').live('click', function(e) {
e.stopPropagation()
e.preventDefault()
var form_el = jQuery(this).parents('form')
var num_questions = form_el.find('.question').length
var new_question_el = form_el.find('.question:last').clone()
new_question_el.appendTo('.questions',form_el).hide().slideDown("fast")
new_question_el.find('label,select,input,textarea').each(function(e) {
var el = jQuery(this)
_.each([ 'class', 'id', 'for','name' ], function(attr_name) {
var attr_val = el.attr(attr_name)
if(attr_val) {
attr_val = attr_val.replace( /_\d+_/, "_"+total_qus+"_" )
attr_val = attr_val.replace( /\[\d+\]/, "["+total_qus+"]" )
el.attr( attr_name, attr_val )
}
})
})
@iamdustan
Copy link

$('body').on('click', 'a.add-new-field', function(e) {
  var self = $(this)
    , tmpl = self.data('template');

  if (tmpl) {
    var newField = $(tmpl).clone();
    self.remove();

    newField.find('label,select,input,textarea').each(function() {
      var el = $(this), num;
      _.each(['class', 'id', 'for', 'name'], function(attr) {
        var val;
        if (val = el.attr(attr)) {
          if (!num) {
            num = val.match(/(_\d+)|(\[\d+\])/)[0];
            num = num.replace(/\_|\[|\]/, '');
            num = parseInt(num, 10) + 1;
          }
          val = val.replace(/_\d+/, '_' +num);
          val = val.replace(/\[\d+\]/, '[' +num+ ']');
          el.attr(attr, val);
          $(tmpl).parent().append(newField);
        }
      });
    });
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment