the __i__
widget instance is a place holder/template for new widget instances when they are create on the UI. Widgets are assigned an actual widget number that will replace the __i__
when they are added to a sidebar and then An ajax request is sent from the UI to the server to update it with the new number, no response is expected from the server for that.
So what happens is that the __i__
instance is just duplicated into the sidebar UI with the only thing being changed is the __i__
being replaced with an actual number on all of the form fields. your JS is not a form field.
Hopefully this explains the why, and why it works after a save (a widget save will probably also solve the problem), as after the save the widget’s HTML is fully generated on the server side and not only emulated in JS.
How to fix? do not add JS snippets in the form. Use classes on the elements you want to make “dynamic” and use the jQuery APIs which can locate the element relative to the currently clicked one. For example, if the element is on the “root” of the widget, get the element parent and find()
the element below it which has the class you want to manipulate.