AngularJS: ensure that only non-empty and dirty form inputs are included in AJAX post requests

My form has an 'Address' section where I submit the data to the server using an $http post request.

If the address fields are left blank (pristine), then the Address information is not included in the object data sent to the server.

However, when I type something in the address fields and then delete what I typed (leaving them blank), empty fields are still included in the JSON post:

{
    street:"",
    city:""
} 

I wish to exclude this optional address data if the fields are left blank.

Is there an easy way to reset individual form fields to their 'pristine' state if they remain empty?

Answer №1

Setting something to pristine must be done manually. Once a form is interacted with, it remains in that state until manually reset.

In addition to checking the pristine status, I would also include a validation for the values in the form field within the update function.

Answer №2

To prevent empty fields from being included in your submitted object, consider using ng-pattern to validate them. Simply add the following code snippet to your controller:

$scope.validateField = /^(.+)$/i

Then, in your HTML markup:

...<input ... ng-pattern='validateField' ... >

If a field is left empty, it will not be included in the submission because it does not match the specified pattern. Otherwise, it will be sent as expected.

Answer №3

To keep track of the value, you can monitor it with a watch function, validate if it's empty, and then revert it to its original state manually

$scope.$watch('inputName',function(newValue){
  if(newValue === "")
     $scope.form.inputName.$pristine = true;
});

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

What is the best way to dynamically load my React component?

Is there a way to dynamically load my React toolbar component based on state changes? constructor(props) { super(props); this.state = { currentPageNumber: 0, }; } render(){ return( <View> ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Conceal the year, month, and day within a datetime-local input

I am working with <input type="datetime-local" step="1"/> input fields, and I want users to only be able to edit the hours, minutes, or seconds. This is due to setting the minimum value using let min = new Date().setHours(0,0,0) and the maximum value ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Limiting the number of rows in pagination using a select option

Having a pagination feature on my page, I now aim to add a new functionality. When the user selects the number of rows from a drop-down menu, the webpage should display matching data. Despite trying to implement this with ajax, the limit variable is not be ...

Tips for implementing camera animation to focus on a specific area of a gltf model when it is clicked in three.js

I've successfully used a gltf loader to load a model and implemented a click function on it. The desired behavior is that when a specific part of the model is clicked, the camera should smoothly transition to focus on that part instead of abruptly cha ...

Change the language of the website using JavaScript/JSON

Creating a website and aiming to utilize JavaScript for the following: If the browser language is set to French, retrieve the text from languageFr.json, otherwise, retrieve the text from languageEn.json. Here is a snippet of the code I have so far: JSON ...

An error occurred during conversion: trying to convert an object to an array

After reading numerous articles about this issue and trying multiple solutions, I am still unable to resolve it! I have been stuck with this error for the past 3 days and I'm hoping someone can assist me. Thank you in advance for any help! My situati ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

Maximizing the effectiveness of utilizing the include function for displaying various external pages within a single <div> element

Would it be more efficient to utilize the include method for displaying various external pages within a single <div>? When I say "more efficient," I am referring to the speed of loading the pages and its effectiveness compared to using ajax and javas ...

incorporating event handlers to references retrieved from bespoke hooks

I have designed a simple custom hook in my React application to manage the onChange events of a specific input element. const useInput = () => { const ref = useRef(null); const handleChange = () => { console.log("Input has been ...

Utilize Angular.js to showcase JSON data

I have the following code snippet, which currently only displays Question Ids. However, what I want is that when I click the Save button, I want to show the questions.id, option.id, and whether selected is true or false below the textbox. The code provided ...

Effortlessly populate the i18n language within ng-grid using AngularJS

I am currently working on an application that utilizes localization (i18n) with AngularJS. For this project, I decided to incorporate a basic ng-grid which can be found here. Here is a snippet of the code I am using: $scope.gridOptions = { data: 'f ...

My functional Chrome web-audio app built with React works seamlessly, but when I try running it in Firefox, I encounter an issue where variables are being

The functionality of this app is smooth in Chrome, but encounters issues in Firefox where certain global variables are showing up as undefined. The reason behind this error and how to resolve it is currently unclear to me. In Chrome, pressing the play but ...

A date picker pops up when the user clicks on an Angular input field of type text

I am looking to edit a dateTime value using Angular/Ionic, but unfortunately there is no dateTime picker available. To work around this issue, I have split the field into separate date and time fields. In order to incorporate placeholder text and format th ...

Using Angular directives to pre-select a default option

I am currently working on a select HTML tag with two options, and I want to set the first option as the default choice. My select element includes Angular directives like ng-change and ng-model. I have attempted to achieve this by adding selected = "select ...

Transform the code to utilize AJAX jQuery

Recently, I developed a Chrome Extension that extracts data from the data-href attribute and applies it to the href attribute from a Google Search. Below is the current implementation: $(document).on("DOMSubtreeModified", function() { var e = $("#sear ...

AngularJS and ASP Controller API encountering CORS problem while being hosted on separate servers within a local network

I am facing an issue with my ASP application hosted on a server within a local network. Whenever I make an OPTION request from AngularJS, it returns a 200 status but throws an error. Below is the GET code in Angular: var config = { headers: { ...

Having difficulty consolidating the data received from the Twilio API

My goal is to retrieve billing data from the Twilio API and store the fetched value in a variable for display on my web application. Despite my attempts with async and await, I've encountered difficulties getting it to function as intended. const twil ...

The showdown between JSON and a hefty JavaScript array

Currently, I am developing a jQuery autocomplete feature that will need to handle between 10 to 20k records. The dataset is static, and I have the option to either retrieve it from a JSON file or embed it directly into the page using a single line of code ...