What could be causing my JavaScript functions to not run when the page model is already filled with data?

I am currently working on a web application using ASP .NET Core 2.0

One of the components in my app is a partial view that includes a form.

To interact with this form, I have an action method within a controller that is triggered by a JS function utilizing AJAX. This action method populates a model and returns the form's partial view along with the corresponding model.

The functionality works smoothly when the model is not populated. However, I encounter an issue when trying to fetch a record from the database after a specific field is filled and then loses focus. The process works initially when the form's model is empty, but once a record is retrieved and the form is populated, the JS function ceases to execute.

In addition, validations for the field also fail to work after loading a record.

Below is the code snippet for the form's partial view:

<form id="myform">
        <div asp-validation-summary="All" class="text-danger"></div>
        <div class="form-group col-lg-2">
            <label asp-for="Client.Name">Client</label>
            <input asp-for="Client.Name" id="ClientName" />
        </div>
        <div class="form-group col-lg-1">
            <label asp-for="Cliente.Phone"></label>
            <input asp-for="Cliente.Phone" id="Phone"/>
        </div>
</form>

The following code snippet represents the JS/AJAX function:

<script>
$("form").on("blur", "#Phone", function () {
    var phone = document.querySelector('#Phone').value;
    alert('select client by phone=' + phone);

    //Send the JSON array to Controller using AJAX.
    $.ajax({
        type: "POST",
        url: "/Home/GetClienteByPhone",
        data: "phone=" + phone,
        success: function (res) {
            $('#myform').html(res);
        }
    })
});
</script>

Finally, here is the controller action method (Controller=Home):

public IActionResult GetClienteByPhone(string phone)
    {
        if (!string.IsNullOrEmpty(phone))
        {
            var model = new FormViewModel();

            model.Client = _db.Clients.Where(c => c.Phone == phone).FirstOrDefault();

            return PartialView("_Form", model);
        }
        return PartialView("_Form");
    }

In my View, I display the partial view within a div element with the id="myform"

If anyone has insights into why this behavior occurs, please share your thoughts.

Thank you

Answer №1

It appears that when you are updating your form using AJAX, the event handlers attached to it are getting removed as well. To ensure that the event handler continues to work, consider delegating it to a parent element that remains unaffected by the form replacement. It seems like you are attempting to use jQuery's delegate handler function, but unfortunately, the delegate itself is being replaced along with the form. To resolve this issue, either refrain from replacing the entire form and just update a specific child element within it, or select a higher-level parent element above the form.

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

Issue: Dependency type ContextElementDependency does not have a corresponding module factory available

After cloning the project from GitLab and running npm install, all dependencies were successfully downloaded. However, upon executing npm start, I encountered an error stating "No module factory available for dependency type: ContextElementDependency." In ...

Tips for extracting data from an XML file using dynamic variables for roots and elements selected from a drop-down menu

As a newcomer to web development, I have taken on the challenge of creating a quotation software for a digital printing company in my spare time. This software aims to provide instant quotes to potential customers. The aspect I am currently struggling wit ...

How to prevent a Javascript Ajax call from retrieving the same string repeatedly from an XML file?

Encountering a challenge where an Ajax call presents the same string multiple times when attempting to autofill a field. This occurs because the URL used in the Ajax call contains the string numerous times within an XML structure. For instance, upon execu ...

After a texture is added, the shine of the Three.js MeshPhongMaterial diminishes

Check out this intriguing Codepen showcasing a white, glossy "cup" loaded using Three's GLTFLoader: https://codepen.io/snakeo/pen/XWOoGPL However, when I try to add a texture to a section of the mug, the shiny cup mysteriously transforms into a lack ...

Can you explain the function of v-bind within Vue?

I recently started learning Vue and decided to follow a video tutorial by Traversy Media on Youtube In the tutorial, the instructor used v-bind but I struggled to understand its usage. Despite my efforts, I still find the documentation a bit challenging ...

Retrieve data from a row in a kogrid when a checkbox is selected

I am working with a kogrid that contains checkboxes in one column. There are two issues that I am facing: How can I retrieve row data when a checkbox is checked or unchecked? I have a save button located outside the kogrid. When this button is clicked, I ...

Integration of elFinder with TinyMCE 4

Has anyone attempted to integrate elFinder into the latest version (4b1) of TinyMCE? The previous implementation seems to be not working. If you have any snippets or tips, please share. Thank you very much. ...

Solving layout issues / Techniques for determining element heights

This new question is in relation to my previous one: How to position relative elements after absolute elements I have updated the JsFiddle from that question to better represent my current HTML, which I unfortunately do not have a URL for at the moment. Y ...

I'm experiencing an issue with my JavaScript code not producing the expected HTML output

This is the HTML code snippet: <body> <p>Below the input bubbles the numbers from 1 - 100 will be printed. Any number that is a multiple of Fizz will have "Fizz" displayed instead of the number, and the same goes for Buzz. If a number is a ...

Caution: It is important for each child to be assigned a distinct key - How to pass an array in

While following ReactJS tutorials on Scrimba, I came across a scenario where id props need to be passed in an array. import React from 'react'; import Joke from './components/Joke.js' import jokesData from './components/jokesDat ...

Optimizing communication of time data in Laravel and Vue.js using Inertia

Currently, I am encountering an issue while working with Laravel Inertia and Vue.js. The problem arises when the time is transferred between Laravel and Vue.js, as it always converts to UTC automatically, which is not what I want. For instance, if I am u ...

The subsequent page fails to load. Issue with the pagination feature

I'm currently stuck trying to implement pagination in my task and it's not functioning as expected. My approach involved creating two buttons with click events attached, along with a data property that changes when the buttons are clicked. This ...

Is my destructing on point?

I'm facing a coding challenge where I believe I have the right solution, but there are certain steps that need to be taken into account before proceeding. It seems like I may be skipping a step which involves de-structuring a value from a target of an ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

What is the best way to format the ASP page in the following layout?

My website showcases images alongside associated labels that are linked to a datalist. The label retrieves text from a stored procedure and I am aiming to format it as follows: IMAGE Label (Text is positioned next to the image, continuing... and droppin ...

Having trouble displaying a JSON response on an HTML page with AJAX

I've written an AJAX function that goes like this: function ajx(){ var ajaxRequest; // This variable makes Ajax possible! try{ // Works in Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Exp ...

Show the array of text by utilizing UmbracoHelper

I'm having trouble figuring out how to showcase a text array in Umbraco. Specifically, I need to display values from a "Repeatable Text String" property in a razor view. Within my Umbraco setup, I have a view that passes a model like this: @inherits ...

Show nested arrays in Vue.js exhibition

As a newcomer to vue, I've been navigating my way around with some success. Lately, I've been dealing with JSON data structured like this: [ { "name": "jack", "age": "twenty", "Colors&qu ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

Ways to manage player motion within a game's code: employing event handlers, utilizing PATCH requests, modifying direction, and manipulating player coordinates through x and

I'm currently working on a lab project and I'm stuck trying to figure out how to control player movement in my maze game. There are several TODOs in the code that I can't seem to complete. If you need more information from me, please ask bef ...