PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 26, 2022

[FIXED] How to clone elements for cakephp elements

 January 26, 2022     cakephp, javascript, jquery, regex     No comments   

Issue

I have made a template (of a set of bunch of html tags which it might be textarea or types of inputs) I want to clone the template. I want to rename the 'name' and 'id' attributes of each element just by replacing the number while cloning. I preffer to use regex in order to do that.

I want to loop through all Html elements and rename the attributes of new elements. e.g.

id="extrainfofiles-0-extrainfofile-extra-info-file-type-id"
for="extrainfofiles-0-extrainfofile-extra-info-file-type-id"
name="ExtraInfoFiles[0][ExtraInfoFile][extra_info_file_type_id]"

To:

id="extrainfofiles--566345634-extrainfofile-extra-info-file-type-id"
for="extrainfofiles--566345634-extrainfofile-extra-info-file-type-id"
name="ExtraInfoFiles[-566345634][ExtraInfoFile][extra_info_file_type_id]"

Any help please.

Here is JsFiddle: https://jsfiddle.net/isaacrajaei/133ko1un/


Solution

/**
 * Add A File
 */
$('#extrainfo-files').on('click', '.extrafile-add', function(){

    // Create the new row
    var $fileList = $('.file-list-extrainfo');
    var $template = $('.extrainfo-file-template').clone();

    var rowId = '-' + (new Date).getTime();
    $template.removeClass('extrainfo-file-template hide').attr('data-id', rowId);

    // Append the new row to the list
    $template.appendTo($fileList);

    // Rename the attributes 
    var $row = $('.file-row[data-id="' + rowId + '"]');
    updateElements($row.selector, 0, rowId);

});


function updateElements(el, from, to)
    {
        $(el).find('[name*="['+from+']"], [id*="-'+from+'-"], [for*="-'+from+'-"]').attr({
            "name" : function(int, input){
                if (input != null){
                    return input.replace('['+from+']', '[' + to + ']');
                }
            },
            "id" : function(int, input){
                if (input != null){
                    return input.replace('-'+from+'-', '-' + to + '-');
                }
            },
            "for" : function(int, input){
                if (input != null){
                    return input.replace('-'+from+'-', '-' + to + '-');
                }
            },
            "value" : ""
        }).end();
    }


Answered By - Fury
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing