Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled.

On the main page, users can navigate through different pages that open and close tabs loaded dynamically using ajax calls. These calls remove the current page and load the new one into a specific div.

In the pages loaded via Ajax, I need to include JavaScript functions that will be used on those pages. However, when I try to call the function, I receive an "Uncaught ReferenceError: soggettiNaturaChangeEvent is not defined" where soggettiNaturaChangeEvent is the function name.

Here is how I am trying to call it in the newEditSoggetti.jsp page:

<form:select id="soggetti_soggettiNatura" path="soggettiNatura" cssStyle="width:300px;" onChange="javascript:soggettiNaturaChangeEvent();">
...
...
...

In that same page, I also include the JavaScript function:

<script id="function1" type="text/javascript">
    alert("soggettiNaturaChangeEvent");
    function soggettiNaturaChangeEvent()
    {
        alert("function soggettiNaturaChangeEvent");
        var natura = document.getElementById('soggetti_soggettiNatura'); 
        var datanascita = document.getElementById('soggetti_soggettiDataNascita');
        var luogonascita = document.getElementById('soggetti_soggettiLuogoNascita');
        var sesso1 = document.getElementById('soggettiSessoID1');
        var sesso2 = document.getElementById('soggettiSessoID2');
        if(natura.value == "Persona fisica")
        {
        datanascita.disabled=false;
        luogonascita.disabled=false;
        sesso1.disabled=false;
        sesso2.disabled=false;
    }
    else
    {
        datanascita.disabled=true;
        luogonascita.disabled=true;
        sesso1.disabled=true;
        sesso2.disabled=true;
    }
}
</script>

My tab refresh function that calls an initScript specified in a parameter looks like this:

//reset stuff, reorder tabs, etc...
$.ajax(action,
{
success : function(result)
{
    //finds the div where to put new content
var doc = document.getElementById(newid);
doc.innerHTML = doc.innerHTML + result;

    //finds the initScript "scriptId" and runs it (THIS IS WORKING)
scripts = $('#' + scriptId); 
eval(scripts.html());

    //here I try to find all the scripts tag that begin with "function" and eval them
    var jScripts = $("[id^=function]");
for(var i = 0; i < jScripts.size(); i++)
{
       eval(jScripts.html());
   jScripts = jScripts.next();
}
}
});

The initial alert message pops up when the function is appended to the DOM, but I get an error when I try to invoke the function by clicking on the component. My goal is to execute this function upon clicking the soggettiNatura component, rather than after the ajax call finishes loading the page.

If there is anyone willing to help me troubleshoot this issue, I would greatly appreciate it. Thank you to all who provide assistance, and to those who have shared valuable information that I have read in the past. Keep up the excellent work.

Andrea

P.S.: Apologies for the poor indentation, as I'm a bit rushed at the moment :P

Edit: Adding a note, when I try loading the page without Ajax, the JavaScript functions work correctly. I have a function on the main page that displays the actual HTML code after the various JavaScript and Ajax modifications (solely for debugging purposes), and the JavaScript function I'm attempting to call is present in the DOM structure. Please assist a newcomer in this realm...

Answer №1

After much effort, I have finally achieved it. Here is a snippet of a web page showcasing all the relevant code:

<%@ page language="java" isELIgnored="false" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<jsp:directive.include file="/WEB-INF/sitemesh-decorators/include.jsp"/>
<fmt:setBundle basename="bundles.settori-resources"/>
<!-- !!!!! important for popup !!!!! A boolean parameter is received from the server to determine whether the page is opening in popup or tab mode -->
<% Boolean isPopup = (Boolean)request.getAttribute("popup"); %>
<!-- !!!!! important for popup !!!!! -->

<div id="contentarea" >
<div id="lb"><div id="rb"><div id="bb"><div id="blc">
<div id="brc"><div id="tb"><div id="tlc"><div id="trc">
<div id="content">
    <h2><fmt:message key="navigation.management"/> <fmt:message key="settori.title"/></h2>
    <div id = "initScriptSettori"></div>
    <form:form id="tabSettoriForm" method="POST" commandName="settori">
        <!-- !!!!! important for popup !!!!! The ID of the element on the calling page that will be edited with the selected element in the popup is stored here -->
        <form:hidden path="hiddenCallerFormElementId" />
        <!-- !!!!! important for popup !!!!! -->
        ...

<!-- !!!!! important for popup !!!!! -->
<script>
function initLoad()
{
//necessary for the popup init script loading
if(jQuery1_6_2("#initScriptSettori").length != 0)
{
    jQuery1_6_2.getScript("javascripts/pagesJs/" + "initScriptSettori" + ".js", function() 
    {
        window["initScriptSettori"]();
    });
}
else
    setTimeout("initLoad()",500);
}
initLoad();
</script>
<!-- !!!!! important for popup !!!!! -->

The initScriptSettori.js:

function initScriptSettori()
{
}

In my scenario, there was no initialization required, but often you may need JavaScript events triggered at the end of page loading. Those can be placed within the `initScriptSettori` function.

I trust this information proves helpful. Enjoy!

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

Learn the process of integrating JSON data into a jQuery Datatable!

I am facing an issue while trying to load data into jQuery Data table using MVC. The data is only displaying in JSON format in the browser instead of populating the data table, as shown below: {"data":[{"ID":1,"FullName":"John Smith","Email":"[email prote ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...

Exploring the capabilities of qTip2 integrated with jQuery Vector Maps (jqvmap)

Is there a way to disable the default tooltip in jqvmap and replace it with qTip2? Check out this example. Here's the jQuery code: jQuery('#vmap').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffff ...

utilizing Javascript to insert a class with a pseudo-element

Witness the mesmerizing shining effect crafted solely with CSS: html, body{ width: 100%; height: 100%; margin: 0px; display: table; background: #2f2f2f; } .body-inner{ display: table-cell; width: 100%; height: 100%; ...

Activate colorbox once the content has been loaded through ajax into a concealed div

How can I trigger colorbox after ajax has loaded content into a hidden div? $('#recipe').on('keyup', function( event ){ if(this.value.length == 3) { /* Perform an ajax call, output the result to div #check-drink */ ...

The hiding/showing of elements is not being executed correctly by jQuery

My web template includes HTML and jQuery code for a project I'm working on. During the $.getJSON call, there can be a delay in loading the data. To inform the user to wait, I added a warning message in a div with the id="warning". The code properly ...

Selecting list items using the up and down keys in JavaScript/jQuery

As the search terms dynamically populate a list of items, I am looking for a way to make the list items selectable/focused using the up/down keys and hide the dropdown with ESC key. <form> <div> <div class="field"> & ...

Utilize jQuery to extract the content, rearrange the content, and then encapsulate it within fresh

I attempted all day to rearrange this menu the way I want, but since I am new to jQuery, I'm facing some challenges. Here is what I am currently trying to achieve: Inside the last td.top of this menu, there are 3 ul.sub li items. I aim to extract ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

Updating the icon with jQuery when receiving AJAX responses

I recently implemented a feature where users can bookmark list entries by clicking on a font awesome link. The bookmarking functionality is working smoothly thanks to AJAX, and the database gets updated as expected. Now, I'm facing an issue with chan ...

What are the steps to create a shadow effect on a bar chart in ChartJs?

Currently, I am utilizing version 3.9 of chartjs to construct a bar chart. My goal is to incorporate a shadow effect on the bars resembling the image in this link: https://i.sstatic.net/SGIrO.png Despite my efforts, I have not been able to locate instruc ...

Error encountered when attempting to upload an attachment in Sharepoint, resulting in a

Whenever I attempt to upload multiple attachments to my list, I encounter a 'save conflict' error. It seems that Sharepoint is still processing the previous attachment when a new one is submitted. I believe that introducing a delay before sendin ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Tips for triggering a method upon the initial passing of props to a Vue.js component

<script> import _ from "lodash"; export default { name: "QuestionBottom", props: { currentQuestion: Object, nextQuestion: Function, increment: Function, }, ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

JavaScript libraries are not required when using the .append function to add HTML elements

Currently, I am attempting to utilize $.ajax in order to retrieve an html string from a php file and append it to the current html div. Oddly enough, when I use php echo, everything functions properly. However, when I attempt to load dynamically using $.lo ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Having trouble showing Bootstrap Toasts on my website

I successfully implemented Toast functionality upon button click, but I am facing an issue where I have two buttons and I want a separate Toast to appear for each button click. How can I achieve this? Another problem I encountered is related to the docume ...