Issue with Selectric plugin not working properly after being dynamically added via jQuery

After clicking a button, I tried to clone form elements and append them to the target using this code.

   $('#addChild').on('click', function () {
                var num     = $('.clonedInput').length, 
                newNum  = new Number(num + 1),      
                newElem = $('#entry' + num).clone().attr('id', 'entry' + newNum).fadeIn('slow'); 

             if (newNum == 4) { 
                    alert("Sorry, You can add upto 3 childrens only");
                    return false; 
             } 

            newElem.find('.heading-reference').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Child #' + newNum);

            // Title - select
            newElem.find('.fnameLabel').attr('for', 'ID' + newNum + '_title');
            newElem.find('.fName').attr('id', 'ID' + newNum + '_fName').attr('name', 'ID' + newNum + '_fName').val('');

            // First name - text
            newElem.find('.surLabel').attr('for', 'ID' + newNum + '_sName');
            newElem.find('.sName').attr('id', 'ID' + newNum + '_sName').attr('name', 'ID' + newNum + '_sName').val('');

            // Last name - text
            newElem.find('.genderLabel').attr('for', 'ID' + newNum + '_gender');
            newElem.find('.genderSelect').attr('id', 'ID' + newNum + '_gender').attr('name', 'ID' + newNum + '_gender');

            // Color - checkbox
            newElem.find('.dobLab').attr('for', 'ID' + newNum + '_dobLab');
            newElem.find('.dob').attr('id', 'ID' + newNum + '_dob').attr('name', 'ID' + newNum + '_dob');

            $('#entry' + num).after(newElem);
            $('#ID' + newNum + '_title').focus();

            $('#btnDel').attr('disabled', false);

        }); 

However, I encountered an issue where the selectric select box does not work for cloned items. I'm unsure of where I've gone wrong. Any assistance on this matter would be greatly appreciated.

If you'd like to see the code in action, please visit this link.

Answer №1

In this innovative approach, you have the option to eliminate the selectric item from the cloned object, reset the select option to default values before adding it to the div, and then initialize selectric in the added select box.

  var clone =  $('.clonedInput').clone();//Create a copy of the input
  clone.find(".clonedInput").val(''); // Clear the selected value

  //Perform the desired action below 
  var default_html = clone.find(".clonedInput").parent('div').html();//Retrieve the HTML content of the select box
  //clonedInputParentDiv refers to the parent div of your cloned input
  clone.find('.clonedInputParentDiv').children('.selectric-wrapper').remove();//Delete all selectric variables from the clone
  clone.find('.clonedInputParentDiv').append(title); // Add title as a regular selectbox within the clone


  clone.find(".clonedInput").selectric();// Initialize selectric in the newly appended select box
  clone.insertAfter('.clonedInput:last');

Answer №2

Prior to using the selectric plugin, make sure to initialize it before calling .clone(), so that the entire element (already altered by the selectric plugin) is duplicated.

It's recommended to clone the element before beginning the plugin initialization process.

// First clone the element before .selectric():
var newEl = $('#entry1').clone();
// Start initializing the plugin:
$(".basic").selectric();
$('#addChild').on('click', function () {

    var num     = $('.clonedInput').length, 
        newNum  = new Number(num + 1),
        // Use the cloned object without selectric data:      
        newElem = newEl.clone().attr('id', 'entry' + newNum).fadeIn('slow'); 

    // ...

    // Ensure you also initialize the plugin for the new ".basic" elements:
    $(newElem).appendTo('.allCatsContainer').find(".basic").selectric();

});

Check out the JSFiddle demonstration here


Furthermore, keep in mind that all replicated <select> elements will have identical ids like #gender, #day, #month, #year.
Adjust these ids accordingly or avoid using them if they're unnecessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

The AppJS warning: A potentially dangerous JavaScript attempt to access a frame with a URL

I am currently working on a desktop application where I am trying to filter specific divs inside an iframe using AppJS. However, I am facing an issue with hiding some of the div elements. Here is the code snippet: <!DOCTYPE html> <html> <s ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...

How to Retrieve the Name of the Active Element from an Unordered List (<ul>) in ReactJS and Display it in the

I have a project where I am creating a long navbar specifically for mobile devices, and I am structuring it in an accordion style. Initially, the view will show the currently active link name. When the user clicks on this active link name, it expands below ...

Feasible: Embedding my complete website using custom HTML code into an iframe

I have the HTML for a website saved in a JavaScript string and I want to display it within an iframe. How can I insert this HTML string into the iframe and make the website appear? I have attempted to use this.src = HTML_STR; this.innerHTML = HTML_STR; but ...

Increment Counter on Presence of Items in a Table with jQuery

Does anyone know how to properly increment a counter in jQuery based on certain words found within a table? I am currently encountering an issue where my counter is only increasing by 1 instead of the expected 2. Here is the HTML and jQuery code snippet: ...

Adding specific props, such as fullWidth, at a certain width, like 'sm', in Material UI React

My goal is to include the fullWidth prop when the screen reaches a size of 600px or greater, which is equivalent to the breakpoint sm. I attempted to implement the following code, but unfortunately, it does not seem to be functioning as intended. [theme ...

Combining two arrays with identical IDs using Angular or JavaScript - a step-by-step guide

As a newcomer to Angular and JavaScript, I am attempting to combine values with the same ID into one row using concatenation. var array = [{ id: "410", value: "val1" }, { id: "411", value: "val1" ...

Is it possible to create a popup window that remains fixed at the top edge of the screen but scrolls along with the rest of the page if

In an attempt to organize my thoughts, I am facing a challenge with a search page similar to Google. The search results trigger a popup window when hovering over an icon, located to the right of the search results. Here is what I am looking to achieve with ...

What is the best way to insert text into a paragraph tag using JQuery?

As part of my learning journey on Codecademy, I decided to challenge myself by creating my very first Chrome extension using HTML/CSS, jQuery, and Javascript. My initial goal is to learn how to append text to a paragraph tag when a button is clicked. Here ...

Retrieve the current system datetime with just a click of a button

Does anyone know how to use JSF + RichFaces to automatically display the current date and time in an inputText field when a button is clicked? Any guidance on this would be greatly appreciated. Thank you! ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

Issues with internal linking in TYPO3 are causing anchor tags to malfunction

When creating an internal anchor, it is usually defined using <a name="anchorname">Introduction</a>. To link to this anchor, you would write something like <a href="#anchorname">Top</a>. In TYPO3, an anchor is a ...

Retrieve data from two databases and display the information from two separate arrays on a single ejs page after making two separate database calls

Currently, I am faced with a challenge where I need to render a page by passing two arrays that are populated by two separate database calls. It seems that when I only pass one array to the ejs page, everything works as expected. For a single array, my a ...

Can you explain the distinction between canvas.width and canvas.clientWidth for me?

I've been diving into three.js and came across an interesting example. The developer starts by creating a canvas element and then connects the renderer to that specific canvas. <canvas id="c"> </canvas> const renderer = new TH ...

Converting a functional component into a class-based component

I am in the process of converting a functional based Component to a class-based Component and creating a PrivateAuth Component. Here is the original PrivateAuth functional Component. function PrivateRoute({ component: Component, ...rest }) { return ( ...

The art of organizing dates and times

Need help with formatting a datetime that is retrieved from the database. The current format is as follows: 2012-06-11 21:39:54 I would like to display it in the format of June 11. Any suggestions on how this can be achieved? Thank you! ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

Using ASP.NET Server Controls to Toggle Textbox Visibility Based on Dropdown Selection

What is the optimal method for displaying or hiding a textbox or an entire div section based on a user's selection from a dropdown menu? I am uncertain if this can be achieved with server controls, so would it require using standard client-side HTML c ...