Remove text from input field and deactivate button upon clicking in AngularJS

I am facing an issue where I want to disable the submit button until some text is entered in the input box.

<div id="app-id-input-container" ng-form="appIdInput">
    <div class="input-group">
        <input id="app-id-input" name="appIdInput" ng-click="clearAppIdInput()" class="form-control" type="text" ng-model="appId" pattern="^[AaIi][PpXxNn][0-9]{6}$" maxlength="8" />
        <span class="input-group-btn">
            <button id="addAppId" class="btn btn-success" ng-click="preferences.appIdInput.$valid && addAppId()" type="button">&nbsp;<span class="glyphicon glyphicon-plus"></span></button>
        </span>
    </div>
    <span class="validation-alert" ng-show="appIdError">{{appIdError}}</span>
</div>

To reset the field, I have a function that clears it when a user clicks inside the input box.

$scope.clearAppIdInput = function() {
    $scope.appId = "";
};

However, even when the field is empty, the button remains enabled. I have a script to disable the button initially and enable it only when text is entered.

$(document).ready(function(){
    $('#addAppId').prop('disabled', true);

    $('#app-id-input').keyup(function(){
        $('#addAppId').prop('disabled', this.value == "" ? true : false);
    });
});

One challenge I'm facing is that pressing "backspace" on the keyboard enables the button again. How can I ensure the button stays disabled only when clearing the input field with a click?

Answer №1

To adhere to the principles of Angular, my suggestion is to utilize the ngDisabled directive:

<button ng-disabled="!userId" id="submitUserId" class="btn btn-primary"
        ng-click="form.userIdInput.$valid && submitUserId()" 
        type="button">&nbsp;<span class="glyphicon glyphicon-check"></span>
</button>

This will effectively disable the button if the value of $scope.userId is empty or undefined. No reliance on jQuery or specialized event handlers is necessary for this functionality.

Answer №2

The field is designed to disable only upon key press detection.

To properly disable the input, make sure to call the disable function after clearing the input:

$scope.clearInput = function() {
    $scope.inputValue = "";
    $('#inputField').prop('disabled', true);
};

Alternatively, follow dhilt's recommendation for a more concise and Angular-friendly solution.

Answer №3

<button id="addAppId" class="btn btn-success" ng-click="preferences.appIdInput.$valid && addAppId()" type="button">&nbsp;<span class="glyphicon glyphicon-plus" ng-disabled="!appId"></span></button>

ng-disabled="!appId" will deactivate the button if $scope.appId is empty, undefined, or null.

Here is a simple example code snippet:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script> 
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.appId = "";
        
        $scope.clearAppId = function(){
          $scope.appId = "";
        }
    });
</script>  
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
    <button class="btn btn-default" ng-disabled="!appId">Disable This</button>
    <input type="text" ng-click="clearAppId()" ng-model="appId"/>
</div>
</body>
</html>

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

Guide to displaying a loading message while performing a synchronous AJAX request in a web browser

Is there a way to display a waiting message during a synchronous AJAX call in the browser? I attempted to use the code below, but even after turning off the web server, the "Saving" message did not appear. After some time, only an error event from the AJA ...

Encountered an error trying to access the length property of an undefined variable while passing props

I need help with my shopping app project. I am trying to create a feature where if the cart is empty, it should display a message saying "shopping cart is empty." However, when I try to implement this, I keep getting a type error that says "Cannot read p ...

Exploring the ng-annotate and resolve features within the ui-router framework

Having an issue with my resolve methods not receiving their injected services. Here is a snippet of my code: (function () { 'use strict'; angular.module('sapphire.sample-limits').config(routes); function routes($stateProv ...

Having trouble altering the error response code in feathers.js

I'm utilizing an authentication service for login validation. In this case, I am looking to change the Unauthorized (401) response code to 200 while keeping the message the same. The authentication service setup is as follows: app.service('auth ...

Is it possible for the success callback in an angular $resource call to access the actual array

Being new to the world of Angular, I am encountering an issue with a custom array ($scope.picking.operations). I can add multiple objects to this array with a boolean 'send' set to false. There is a button that triggers sending this data to the s ...

When navigating back, the Bootstrap Multistep Form breaks down

Tools I'm currently utilizing: HTML, CSS, Javascript, Bootstrap 3 Library / Package in use: https://codepen.io/designify-me/pen/qrJWpG Hello there! I am attempting to customize a Codepen-based Bootstrap Multistep Form from the provided link abov ...

Switch the parent container in AngularJS by utilizing ng-click functionality

Within two distinct containers, one container holds a button. Upon clicking it, this button should move to the second container. I am familiar with achieving this using jQuery: $(document).on('click', '.drag', function(){ if($(thi ...

Is there a way to change the font size with a click in JavaScript or Angular?

Here is a breakdown of the 4 steps: 1.) Begin by clicking on a category 2.) The filtered products will be displayed 3.) Select the desired products from the filter 4.) Once selected, the products will appear in the rightmost part of the screen within t ...

Changing the opacity of the background when a Bootstrap modal is displayedHere's how you can

While working with a bootstrap modal, I noticed that the background content opacity does not change by default when the modal is open. I attempted to change this using JavaScript: function showModal() { document.getElementById("pageContent").style.opaci ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Is there a faster way to sort this data with Javascript (or JQuery for extra speed)?

Recently, I've encountered a challenge with sorting an HTML table using JavaScript. The table can potentially contain over a thousand rows. This is what my current setup looks like in terms of HTML: <div id="mycollection" class="table"> &l ...

Who is responsible for the addition of this wrapper to my code?

Issue with Sourcemaps in Angular 2 TypeScript App Currently, I am working on an Angular 2 app using TypeScript, and deploying it with the help of SystemJS and Gulp. The problem arises when I try to incorporate sourcemaps. When I use inline sourcemaps, eve ...

What is the reason behind the controller being unable to locate an Angular model when it contains dots in its name?

I am completely new to Angular and struggling to comprehend this code snippet. app.controller('FileConfigController-detail', function($scope, $http, $stateParams, FileConfigDetailsService) { $scope.detail.inptITResourceID = "test me" ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

An issue arose in nodejs when attempting to use redirect, resulting in the error: "Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers after they have

I am currently working on a project where I encountered an unexpected error. My goal was to redirect the server to specific routes based on certain conditions, but I am facing difficulties. routes.post("/check", (req, res) => { console.log(& ...

How can Angular retrieve products by sending a get request to an API?

I'm looking to showcase products on a website and I need to retrieve them by making a GET request to an API using Angular. I've attempted to follow the Angular documentation, but I can't seem to get it working. Any guidance or assistance wou ...

Using Javascript to link object-oriented programming methods to events and better understand the 'this' keyword

I am currently learning OOP Javascript but struggling with understanding the this keyword and working with events. My goal is to bind a common event to multiple DOM objects while storing data about these objects in a global container for better performanc ...

Unable to avoid IE8 warning about reposting using client-side code

When using asp.net webforms, every server control generates a post request when clicked. If you try to reload the page with F5 or Ctrl+R after that request, the browser will show a re-post warning by default. In an attempt to avoid this behavior in IE 7-* ...

The 'ReactType' type is not generic within material-ui@next

After installing material ui@next, I encountered an error in the node modules. ERROR in [at-loader] ./node_modules/material-ui/Avatar/Avatar.d.ts:8:15 11:31:52 web.1 | TS2315: Type 'ReactType' is not generic. 11:31:52 web.1 | ERROR in ...

Shutting down a React Semantic UI modal using a combination of a button and a close

I've created a Modal where users must fill out forms and save the entered information by clicking a button within the Modal. However, I'm facing an issue - even though I can close the Modal using the open prop on the Modal component, I'm una ...