Speed up development with full-stack environments for every branch.

Learn More

Add & Remove form elements dynamically [jQuery, javascript]

Forked from How to use the jQuery $().ready function.

2465 Runs 4937 Views 3134 Copies

フォームを追加したり削除したり (元ネタ:http://code.runnable.com/U7brTcACcG8MGzIm/add-form-elements-simple-for-jquery-and-javascript)

Saved

Saved

SiskAra 2

SiskAra
published 2 years ago

    $(function () {
        var frm_cnt = 0;
        
        $(document).on('click', '.add', function(){
          var original = $('#form_block\\[' + frm_cnt + '\\]');
          var originCnt = frm_cnt;
          var originVal = $("input[name='sex\\[" + frm_cnt + "\\]']:checked").val();
          
          frm_cnt++;
          
          original
              .clone()
              .hide()
              .insertAfter(original)
              .attr('id', 'form_block[' + frm_cnt + ']') // クローンのid属性を変更。
              .find("input[type='radio'][checked]").prop('checked', true)
              .end() // 一度適用する
              .find('input, textarea').each(function(idx, obj) {
                  $(obj).attr({
                      id: $(obj).attr('id').replace(/\[[0-9]\]+$/, '[' + frm_cnt + ']'),
                      name: $(obj).attr('name').replace(/\[[0-9]\]+$/, '[' + frm_cnt + ']')
                  });
                  if ($(obj).attr('type') == 'text') {
                    $(obj).val('');
                  }
              });
    
          // clone取得
          var clone = $('#form_block\\[' + frm_cnt + '\\]');
          clone.children('span.close').show();
          clone.slideDown('slow');
          
          // originalラジオボタン復元
          original.find("input[name='sex\\[" + originCnt + "\\]'][value='" + originVal + "']").prop('checked', true);
    	  });
    
        $(document).on('click', '.close', function(){
            var removeObj = $(this).parent();
            removeObj.fadeOut('fast', function() {
                removeObj.remove();
                // 番号振り直し
                frm_cnt = 0;
                $(".form-block[id^='form_block']").each(function(index, formObj) {
                    if ($(formObj).attr('id') != 'form_block[0]') {
                        frm_cnt++;
                        $(formObj)
                            .attr('id', 'form_block[' + frm_cnt + ']') // id属性を変更。
                            .find('input, textarea').each(function(idx, obj) {
                                $(obj).attr({
                                    id: $(obj).attr('id').replace(/\[[0-9]\]+$/, '[' + frm_cnt + ']'),
                                    name: $(obj).attr('name').replace(/\[[0-9]\]+$/, '[' + frm_cnt + ']')
                                });
                            });
                        }
                });
    		    });
        });
    });
    Please login/signup to get access to the terminal.

    Your session has timed out.

    Dismiss (the page may not function properly).