I have a huge form which dynamically hides or shows elements, depending on the input. For this, I'm using a lot of onChange events. The form can be submitted to, and is loaded using a PHP server. The form itself uses Javascript and JQuery. When the form is loaded, the onChange events are not automatically triggered, so I tried doing it manually with the following code:
//Fires the event manually
echo 'var element = document.getElementsByName("'.$FieldName.'");';
echo 'event = new Event("change");';
echo 'element.dispatchEvent(event);';
The console tells me that "element.dispatchEvent is not a function". I did some research and tried to put
<script src="DynamicForm.js" type="text/javascript"> <!--Contains the JQuery code--> </script>
<script>$.noConflict(true);</script>
<script> <!--Code that fires the event manually here--> </script>
That still gave me the "element.dispatchEvent is not a function" error. Despite that, I'd have to change the whole JQuery code, which will probably give me some new errors, so I do not necessarily want to do that. Is there a (more efficient) way to solve my issue? I appreciate any assistance.
The error you are getting is because "element" in your code hasn't been found by your document.getElementsByName code. The use of .getElementsByName is depreciated many years ago. It will also return an array of objects if it matches multiple names.
Instead you should use getElementById() if you want to use pure javascript, or you can achieve what your wanting to do in a single line with jQuery;
$('#formFieldID').trigger("change");
Where formFieldID is the ID of the form field as declared in your html.
I think you are trying to manipulate DOM element before their creation.
You can ask jQuery to wait until the DOM is complete with $(function() { /* code */ })
or, a quicker and newer version, $(() => /* code */)
.
Plus, you can directly trigger an event with jQuery, it will be easier if you use custom event or namespaced event.
echo '$(() => $("[name=\"'.$FieldName.'\""]).trigger("change"));';
To simplify your code, I suggest to use a dedicated class to trigger the event. You can place this directly in the JS code and not in the PHP part.
$(() => $(".js-trigger-change").trigger("change"));