Experiencing difficulties with AngularJs as onblur event is not functioning properly when the input field is empty

I am currently working on a form that allows users to input data. I am facing an issue where if a user enters a number, deletes it, and moves away from the input field, it will display an error message. However, I want the error message to display only if a user clicks into the field and then clicks out without adding a number. I am puzzled as to why the onblur event is not functioning as expected, especially since I followed two tutorials that used the same approach.

<form name="myform" novalidate>
        <table class="text-center margin-top">
            <tr>
                <th class="header">Course Type</th>
                <th>Amount of Times</th>
                <th>Frequency (PA)</th>
                <th>% Staff who need it</th>
            </tr>
            <tr>
                <td class="header"><label for="induction">Induction:</label></td>
                <td><input class="form-control" type="number" id="inductionAmount" name="inductionAmount" ng-model="staff.inductionAmount" ng-model-options="{ updateOn: 'blur' }" ng-required="true" /></td>
                <span class="error-message" ng-show="!myform.inductionAmount.$pristine && myform.inductionAmount.$error.required">Please enter an induction value</span>
                <td><input class="form-control" type="number" id="inductionFrequency" name="inductionFrequency" ng-model="staff.inductionFrequency" ng-required="true" /></td>
                <span class="error-message" ng-show="myform.inductionFrequency.$dirty && myform.inductionFrequency.$error.required">Please enter an induction value</span>          
                <td><p>100</p></td>             
            </tr>       
        </table>
        </form>
    </div>
</div>  

<div class="row margin-top">
    <div class="col-sm-4 col-sm-offset-4">
        <button type="submit" ng-disabled="myform.$invalid" class="button-orange" style="font-size: 16px; font-weight: 700;" ng-click="clicked()">Next Step</button>
    </div>
</div>      

Answer №1

When a user clicks into a field but then clicks out without adding a number, I want it to be displayed.

To achieve this, instead of using !$pristine, you can utilize $touched:

This property is true when the control has lost focus.

This functionality has been available since version 1.3.20. The input will only be marked as not pristine or dirty if the user interacts with the input, for example, by making a change.

<span class="error-message" ng-show="myform.inductionAmount.$touched && myform.inductionAmount.$error.required">Please enter an induction value</span>

For a demonstration, check out this plunker.

EDIT

If you are using an older version, you can replicate this behavior using the ngBlur directive with

ng-blur="myform.inductionAmount.$touched=true"

<input class="form-control" type="number" id="inductionAmount" name="inductionAmount" ng-model="staff.inductionAmount" ng-required="true" ng-blur="myform.inductionAmount.$touched=true"/></td>
<span class="error-message" ng-show="myform.inductionAmount.$touched && myform.inductionAmount.$error.required">Please enter an induction value</span>

View this in action on plunker

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

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

Improving efficiency by saving and loading the form value using best practices

One of the challenges I'm facing is how to populate dropdown selections on a webpage without resorting to hard-coded procedures. The code snippet below illustrates the current setup: <td> <ui-select ng-model="user_profile.gender" require ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Issue with Route Transition in React Router version 4 when using Styled Components

I am currently in the process of constructing a React Application utilizing React-Router@4, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5e7d0d4d6c198fddac198f9dad4d1d0c7f5869bd7d0c1d49b83">[email protected]</a> ...

Discovering inappropriate behavior in filtered results

I am attempting to locate projects based on their project IDs. To achieve this, I am utilizing the following filter method: $scope.filteredPro = $filter('filter')( project.ProjectSummaryFilter, {"ProjectId" : "1" } ); However, the issue arises ...

Sign up for the observable, retrieve the asynchronous mapped outcome with input from the dialog, and then utilize the outcome from the map

Currently, I am utilizing an API-service that delivers an Observable containing an array of elements. apiMethod(input: Input): Observable<ResultElement[]> Typically, I have been selecting the first element from the array, subscribing to it, and the ...

I have decided to integrate Laravel with Vite for building CSS and JS. However, when I attempted to run `npm run dev`, it appeared to execute but was accompanied by an error in the background that

Hi there, I'm new to Laravel and I've created a small app that primarily uses CSS and JS scripts. Everything was working fine in my development environment, so I decided to push it to a production server. However, after installation, my code does ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

Retrieving information from a MYSQL database table and populating a text field with AJAX and PHP

Is there a way to use AJAX to display the data from an array that is called in getword.php into a text field in index.php? Let's take a look at the code below: Here is the code snippet from index.php: <body> <div class="container" ...

Learn the methods for successfully transferring dynamic values from Angular to a jQuery script

This is the script that I have included in my HTML code: <div class="progress-bar"></div> <script type="text/javascript"> $('.progress-bar').gradientProgressBar({ value: $(this).attr('$scope.moodvalue'), ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

Fixing the Material UI upgrade error: "Make sure you have the right loader for this file type."

As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...

Applying hover effect to material-ui IconButton component

As stated in the React Material-UI documentation, I have access to a prop called hoveredStyle: http://www.material-ui.com/#/components/icon-button I intend to utilize the IconButton for two specific purposes: Make use of its tooltip prop for improved ac ...

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Ajax: The response from xmlhttp.responseText is displaying the entire inner HTML rather than the specified text needed

This is my Ajax function. It is functioning correctly, however after the function is called, it returns a response containing HTML tags and required text. Response in value variable " <br/> <font size='1'> <table class='x ...