Highlighted

jQuery: reinit selector function when dynamically adding elements to DOM

LEGEND ,
Dec 19, 2017

Copy link to clipboard

Copied

Hello, all,

I'm using jQuery for many things on a page with a form, and I've encountered something that I'm not quite sure what the best way to approach it is.

For example, I'm using .clone() on a small section of the form (it's a cost estimate form in which the user can dynamically add items to the form) and part of the section contains checkboxes.  Depending upon which checkboxes are checked, certain selects (initially disabled) will become enabled and the user prompted to choose an option.  (Five checkboxes, four selects.)

At the bottom of the page, I have the following code to perform the above functionality whenever a checkbox is checked or unchecked:

$('.airLiner').on('click',function(){setRateType();}); // it just calls a function whenever a checkbox is changed.

The function has a lot of code, so for brevity I won't post all of it:

function setRateType(){

     for(var x = 0; x < cdLen; x++){

          var $selectedCksList = $('[name=airLiner-' + x + ']:checked').map(function(i,el){return el.value;}).get().join(',');// Creates a comma-delimited list of values.

          {switch/case: if itemA is found, enable select 'rateType' - else disable}

          {switch/case: if itemB is found, enable select 'movementType' - else disable}

          ...

          {switch/case: if itemG is found, enable select 'action' - else disable}

          }

     }

The issue is that if a user clicks the button to add an item, creating elements on the fly and adding to the DOM, the new checkboxes aren't initialized from when the page loads, like the first checkboxes are.

What is the best way to reinitialize, or whatever is best, the new checkboxes so that they are included in the onClick function?

Is this making sense?

V/r,

^ _ ^

Adobe Community Professional
Correct answer by B i r n o u | Adobe Community Professional

I'm not really sure to get what you mean... but if your problem is to get a portion cloned as it was initilay set (at start)  ... why don't you get a dummy dead hidden portion, like an HTML component set aside and clone that one. This portion will also be the only one ready to get the events... (and not having an already existing HTML portion of the form to be cloned)...

second when you clone the element are you passing two boolean TRUE parameter... the first one for activating the data and the event, and the second one for the deep levels ?

I'm not sure one to got your points, and second to be clear on my answer... please don't hesitate to let me know

Views

2.4K

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

jQuery: reinit selector function when dynamically adding elements to DOM

LEGEND ,
Dec 19, 2017

Copy link to clipboard

Copied

Hello, all,

I'm using jQuery for many things on a page with a form, and I've encountered something that I'm not quite sure what the best way to approach it is.

For example, I'm using .clone() on a small section of the form (it's a cost estimate form in which the user can dynamically add items to the form) and part of the section contains checkboxes.  Depending upon which checkboxes are checked, certain selects (initially disabled) will become enabled and the user prompted to choose an option.  (Five checkboxes, four selects.)

At the bottom of the page, I have the following code to perform the above functionality whenever a checkbox is checked or unchecked:

$('.airLiner').on('click',function(){setRateType();}); // it just calls a function whenever a checkbox is changed.

The function has a lot of code, so for brevity I won't post all of it:

function setRateType(){

     for(var x = 0; x < cdLen; x++){

          var $selectedCksList = $('[name=airLiner-' + x + ']:checked').map(function(i,el){return el.value;}).get().join(',');// Creates a comma-delimited list of values.

          {switch/case: if itemA is found, enable select 'rateType' - else disable}

          {switch/case: if itemB is found, enable select 'movementType' - else disable}

          ...

          {switch/case: if itemG is found, enable select 'action' - else disable}

          }

     }

The issue is that if a user clicks the button to add an item, creating elements on the fly and adding to the DOM, the new checkboxes aren't initialized from when the page loads, like the first checkboxes are.

What is the best way to reinitialize, or whatever is best, the new checkboxes so that they are included in the onClick function?

Is this making sense?

V/r,

^ _ ^

Adobe Community Professional
Correct answer by B i r n o u | Adobe Community Professional

I'm not really sure to get what you mean... but if your problem is to get a portion cloned as it was initilay set (at start)  ... why don't you get a dummy dead hidden portion, like an HTML component set aside and clone that one. This portion will also be the only one ready to get the events... (and not having an already existing HTML portion of the form to be cloned)...

second when you clone the element are you passing two boolean TRUE parameter... the first one for activating the data and the event, and the second one for the deep levels ?

I'm not sure one to got your points, and second to be clear on my answer... please don't hesitate to let me know

Views

2.4K

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Dec 19, 2017 0
Adobe Community Professional ,
Dec 19, 2017

Copy link to clipboard

Copied

In theory, there are two ways to tackle this, namely

  1. re-run the related function after the checkboxes have been added
  2. have the checkboxes available in a display:none element right from the start, to be displayed when needed.

My preference would be the latter.


Ben

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 19, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

Hello, Ben,

BenPleysier  wrote

In theory, there are two ways to tackle this, namely

  1. re-run the related function after the checkboxes have been added
  2. have the checkboxes available in a display:none element right from the start, to be displayed when needed.

My preference would be the latter.

I've tried #1.  In the code after the .clone(), I run setRateType(); but it doesn't seem to be passing the event handler to the new checkboxes.  As far as #2, this would be great if I were limiting the user to just one additional item; but I have no idea how many items any given user may need to add, so I'm allowing unlimited ability to add items to the request.

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
Adobe Community Professional ,
Dec 19, 2017

Copy link to clipboard

Copied

I'm not really sure to get what you mean... but if your problem is to get a portion cloned as it was initilay set (at start)  ... why don't you get a dummy dead hidden portion, like an HTML component set aside and clone that one. This portion will also be the only one ready to get the events... (and not having an already existing HTML portion of the form to be cloned)...

second when you clone the element are you passing two boolean TRUE parameter... the first one for activating the data and the event, and the second one for the deep levels ?

I'm not sure one to got your points, and second to be clear on my answer... please don't hesitate to let me know

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 19, 2017 2
Adobe Community Professional ,
Dec 19, 2017

Copy link to clipboard

Copied

now if I miss understood your initial point, and if your trouble is only that the new created element wont get any event... instead of attaching event to the initial items, did you try to delegate them ?

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 19, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

Hello, Birnou,

A dummy dead hidden group of elements to clone would not be different from cloning the first set; when the elements are cloned and added to the DOM, the new checkboxes would still not have the event handler attached to them.

Your second suggestion of using two true flags (I am currently using true, false) I will implement and see if that works.  Thank you for the suggestion.

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

I have no idea why I was passing the second argument as false, but changing it to true fixed it.  The cloned checkboxes now have the event handler of the originals.    Thank you!


V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
Adobe Community Professional ,
Dec 20, 2017

Copy link to clipboard

Copied

cool that it was helpfull.

when cloning I also often forgot to set this second parameter , and that was often an issue... , since I try to not forget it

anyway, when the need of clone is around, I now create a sort of HTML component ready to be use (for cloning) and I often use a delegation for adding and handling event...

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
Adobe Community Professional ,
Dec 20, 2017

Copy link to clipboard

Copied

how do you handle the event for autocomplete

say it is something like

something.autocomplete()

try to delegate this action as

something.on('focusin', your target, the call)

and inside this called block function having a

$(this).autocomplete

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

The code for autocomplete is the very last JavaScript on the page.  When I first noticed this issue, I placed that code inside a function and called the function as the last line of code, then added a call to that function within the function for adding items, to reinitialize it.  It still isn't working.

function addCargo(){

     ...

     reinitAC(); // last line of this function

     }

...

function reinitAC(){  // AC = autocomplete

     var odArray = #application.odArray#; // ColdFusion application variable that contains over 27k items in an array.

     $('.ogeo').autocomplete({

          source: odArray,

          minLength: 2,

          focus: function(event,ui){ $(this).val(ui.item.value); return false; },

          select: function(event,ui){ $(this).val(ui.item.value.trim()); return false; }

          });

     } reinitAC();

It will not reinitialize the autocomplete.

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

I just noticed something very odd in F12.  Inspecting the element that is cloned and should have the autocomplete, it has an attribute added that I am not adding: autocomplete="off".

WTF???  How is that getting in there???

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

I've placed code that will strip the autocomplete="off" from the text input if it has the 'ui-autocomplete-input' class.  It's not changing anything - the cloned fields will still not autocomplete.  fml.

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
Adobe Community Professional ,
Dec 20, 2017

Copy link to clipboard

Copied

I don't have any part of the logical cloning, and the architecture that you handle, but just from the top of my head , instead of doing

      $('.ogeo').autocomplete({              source: odArray,              minLength: 2,              focus: function(event,ui){ $(this).val(ui.item.value); return false; },              select: function(event,ui){ $(this).val(ui.item.value.trim()); return false; }              });         } ; 

could you try something like

         $('.ogeo').on('focusin',HTMLTarget, function(){          $(this).autocomplete({              source: odArray,              minLength: 2,              focus: function(event,ui){ $(this).val(ui.item.value); return false; },              select: function(event,ui){ $(this).val(ui.item.value.trim()); return false; }            });       })  

well, if that does the job we should then think to flag it , o use a closure, to avoid re loading everytime...

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0
LEGEND ,
Dec 21, 2017

Copy link to clipboard

Copied

Unfortunately, your sample code isn't changing it.    Same thing - the original autocomplete fields work, any/all cloned fields do not.  I've added a call to the reinit function to the end of the clone function, hoping to initialize all fields with that class, and it still doesn't work.

I'm about this >< close to scrapping the autocomplete and use a SELECT generated from the array.  Which feels so.. hackish.. dirty.

(shudder, cringe

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 21, 2017 0
Adobe Community Professional ,
Dec 21, 2017

Copy link to clipboard

Copied

sorry I was between different projects that didn't let me time to produce a working sample... so ...

instead of keep going your way, I prefer use a less confusing solution. That is the reason I've first proposed you to have an hidden 'web component' ready to be fire as cloning ressource... so

Cloning Autocomplete - JSFiddle

cloning an hidden part should resolve many traps... I've use the available tags from jquery... so stuck on A or B... there are plenty results

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 21, 2017 0
LEGEND ,
Dec 22, 2017

Copy link to clipboard

Copied

Thank you, Birnou, but I really don't see how cloning a hidden set of fields will be any different from cloning one that is actively being used.  A clone is a clone.

But it does not matter, as I have scrapped the autocomplete idea and am using an application variable to store all of the values within <option> tags and place them between <select> tags.  It takes half a second to load the page, and I don't have to worry about whether or not event handlers will be cloned from the original.  The autocomplete looked great, when it worked, but I've already wasted too much time on it and need to meet a short deadline.

Thanks for your insight.

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 22, 2017 0
Adobe Community Professional ,
Dec 22, 2017

Copy link to clipboard

Copied

it's up to you, .. personnaly I prefer un autocomplete which is very well adapted on long list of proposal... if you just have a small range of option, the select is definitly a way to go,...

anyway , whatever your choice, you have access to a working exemple on the link...

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 22, 2017 0
Adobe Community Professional ,
Dec 22, 2017

Copy link to clipboard

Copied

youps, I've pressed the answer button too fast...

well, it is not a matter of cloning, it's the way the cloning is done, and most, the way the autocomplete is applied to the appropriated field... not over a general class, but directly to the appropriate child of the just created clone.  do you get the point ?

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 22, 2017 0
LEGEND ,
Dec 22, 2017

Copy link to clipboard

Copied

Slightly different from what I had (I wasn't using .children() ), a very good example.  If I had more time, I would experiment with that.  Perhaps I will push this version and come back to try it, when I have time.

Thank you,

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 22, 2017 0
Adobe Community Professional ,
Dec 22, 2017

Copy link to clipboard

Copied

you're welcome

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 22, 2017 0
LEGEND ,
Dec 20, 2017

Copy link to clipboard

Copied

Aaaaaaaaaaaand another issue has cropped up. 

I am using jQuery autocomplete on several text input fields.  Even with both clone flags being set to true, the autocomplete is only working on the original fields; the cloned fields are not populating with suggested items.

**headdesk**  **headdesk**  **headdesk**

V/r,

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Dec 20, 2017 0