Ensure that the input field retains its content after submission in an AngularJS application

HTML

<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
    <input type="text"  ng-model="user.userFirstName">
    <label class="control-label">Last Name</label>
    <input type="text"  ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form> 

JS

app.controller('updatecontroller', function ($scope, $http, $cookieStore) {

$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
        then(function (response) {
            $scope.user = response.data;
        });$scope.user = {"id": "","userFirstName": "","userLastName": ""}

$scope.updateUser = function () {

    var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
    var method = "PUT";
    $http({
        method: method,
        url: url,
        data: angular.toJson($scope.user),
        headers: {
            'Content-Type': 'application/json'
        }
    })
};});

values are displayed in text fields and can be updated. The values will also update in the database. However, I want the updated values to remain in the form after submission.

Thank you!

Answer №1

To clear the input field after receiving a response from an HTTP request, you can use the following code snippet:

$scope.updateUser = function () {
$http({
    method: 'POST',
    url: 'myUri', 
    data: 'your data'
    headers:'header'
}).then(
    function(res) {
      $scope.user = {"id": "","userFirstName": "","userLastName": ""} //This code clears the input field

    },
    function(err) {

    }
);
}

Answer №2

Make sure to nest your Submit Button within the Form Element before testing it out; you'll notice that it automatically clears the input field after submission.

Answer №3

It appears that the issue lies within your updateUser() function. It seems to potentially be causing the deletion of either user.userFirstName, user.userLastName, or even the entire user object.

To further investigate, could you kindly provide us with a snippet of code from your updateUser() method?

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

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Script for tracking user activity on Facebook and Google platforms

I currently have Google tracking conversion set up, but now I also need to implement Facebook pixel tracking. My existing Google Head Script code is as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||fu ...

Incorporating JavaScript and Alpine.js to Monitor and Log Changes in Input Range Values

I have developed a basic app that logs the input range value to the console when the range input changes. Interestingly, it works flawlessly when I slide the slider left and right with my cursor. However, when I programmatically change the value using Ja ...

using recursion within callback functions

In my JavaScript function with a callback, I am utilizing the "listTables" method of DynamoDB. This method returns only 100 table names initially. If there are more tables, it provides another field called "LastEvaluatedTableName", which can be used in a n ...

The absence of a flickering flame is noticeable in the THREE.js environment

I have been working on creating a flame using THREE.js and spark.js. However, even after rendering the world, I am unable to see the flame and it seems like the world is empty. Although I checked the console for errors, there are no indications of what mig ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Creating sequential numbers using jQuery

Recently, I worked on a script (credit to Chyno Deluxe) that generates a list of menu items based on what is written in the input box. However, I now have a new requirement which involves generating a sequence of numbers to be added continuously. Here is ...

Is there a way to incorporate an external JavaScript file into a .ts file without the need for conversion?

I have an external JavaScript file that I need to utilize in a .ts file without performing any conversion. Does anyone know how to use it within TypeScript without the need for conversion? ...

What is the best way to adjust star ratings in a database table after a page refresh using JavaScript?

I am looking to provide users with the ability to change the rating value of a product, but I'm encountering issues with it not working after the page is refreshed. For instance, a user can freely change the rating value of a new product multiple time ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

What steps do I need to take to integrate AngularJS with the ServiceStack FallbackRoute attribute in order to enable support for HTML5 pushstate URLs?

Currently, I am in the process of developing a client/server solution which involves using an AngularJS Single Page App as the client component and a Self-Hosted ServiceStack RESTful API as the server component. The setup consists of HTML and JavaScript fi ...

Inconsistencies in AngularJS ng-checked functionality

Currently, I am utilizing angularjs in conjunction with an edit view for a form. My goal is to bind the values that were previously used. Below is the code/HTML snippet that I am working with. In addition to angularjs, I am also implementing typescript fol ...

Setting up a React Package by reinstalling a git repository

While immersing myself in learning React JS, I decided to create a git repository containing React components that could be exported and used or installed as a package in a separate React application. I developed some UI Components in a git repository and ...

Utilize Javascript to convert centimeters into inches

Can anyone help me with a JavaScript function that accurately converts CM to IN? I've been using the code below: function toFeet(n) { var realFeet = ((n*0.393700) / 12); var feet = Math.floor(realFeet); var inches = Math.round(10*((realFeet ...

gdal.vectorTranslate causing output files to be void

Attempting to use gdal-async in nodejs for converting vector files from geojson to dxf. const dsGeoJSON2 = gdal.open('./upload2/objects.geojson'); const out2 = gdal.vectorTranslate('./upload2/objects.dxf', dsGeoJSON2, ['-f', ...

Scrolling seamlessly on websites with a single page

I am developing a single-page website that uses different section IDs instead of multiple pages. It's functioning properly, but I want to implement smooth scrolling to the sections rather than just statically jumping to them on the page. Jsfiddle: ht ...

Bring in d3 from unpkg

Uncertain of which file to import, I am seeking guidance on how to import d3 from unpkg.com. Can someone advise me on the equivalent unpkg version of: import * as d3 from "d3"; ...

Fixing Bugs in Checkbox Functionality using useState in Reactjs when implementing Material UI

I am working on a numeric select functionality where selecting a number renders the component multiple times. Inside the component, there are checkboxes that should not all activate at once when one is selected. https://i.sstatic.net/Q5Csn.png You can vi ...

The UI grid in Angular JS is failing to refresh and display the latest content

I am currently utilizing $http.get to retrieve fresh data from the server for an angular ui grid. Whenever the date in the datepicker is altered, I trigger an ng-change event to initiate another http call for updated content. Although the call is successfu ...

Tips for redirecting to a 404 page when encountering invalid data in getStaticProps

For my Next.js application, I need to retrieve all articles written by a specific author. The author's ID is obtained from the request parameters. I have already pre-generated some authors using getStaticPaths. Within the getStaticPaths function, I h ...