Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success.

I attempted the following code but couldn't get it to update. The ng-change is working as expected, so it seems to be an issue with updating the css.

CSS:

// ... more classes
.form-control-error:focus {
    border-color: #FF0000;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}  
.form-control-success:focus {
    border-color: #5cb85c;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

JS:

$scope.changeEmail = function () {
    console.log('change');

    $scope.formControlColor = function () {
        return 'form-control-success';
    };
};

HTML:

<input type="text" id="email" ng-model="email" ng-change="changeEmail()" placeholder="email" ng-class="{'form-control-error': !formControlColor()}" class="form-control input-lg margin-bottom-15">

Answer №1

formControlColor is a function that will provide the necessary class. If you wish to use this return value in ng-class, simply call the function.

<input ... ng-class="formControlColor()" ... />

To ensure the function has an initial definition and displays the correct class when the page loads, your JavaScript code should be similar to:

$scope.formControlColor = function(){
    return 'form-control-error';
};
$scope.changeEmail = function () {
    console.log('change');

    $scope.formControlColor = function () {
        return 'form-control-success';
    };
};

If the value remains constant and doesn't require any complex computation, you can eliminate the function and directly use a string instead. In that case, it would look like:

HTML

<input ... ng-class="formControlClass" ... />

JavaScript

$scope.formControlClass = 'form-control-error';

$scope.changeEmail = function() {
    $scope.formControlClass = 'form-control-success';
}

Answer №2

To set the return value as the setter and include the options in the ng-class object, you can use the following approach. If formControlColor evaluates to false, it will display an error CSS; otherwise, it will show a success CSS:

    <input type="text" id="email" ng-model="email" ng-change="changeEmail()" placeholder="email" 
ng-class="{'form-control-error': !formControlColor, 'form-control-success': formControlColor}" class="form-control input-lg margin-bottom-15">

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

jQuery - translating and organizing names of countries

I have implemented a jQuery function to organize a list of country names based on the user's selected language code (via a language select dropdown). You can find more information on this topic in this related post. The translation of country names s ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

Retrieving information from a Rowdatapacket with expressjs

Is there a way to use a loop to retrieve a single value from each row in RowDataPacket? Currently, my results look like this: [ RowDataPacket { id: 522, number: '111', test: 'testing' }, RowDataPacket { id: 523, number: '112' ...

Disabling a button following a POST request

Is there a way to prevent multiple clicks on a button after a post request is made? I want the button to be disabled as soon as it is clicked, before the post request is executed. Below is an example of my code where the button is supposed to be disabled w ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Dynamically assigning anchor tags to call JavaScript functions

Creating a list dynamically, full of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags. This list is then appended to a div. ...

Personalizing the User Interface of Azure AD B2C using dynamic HTML

After customizing my own html and CSS for Azure AD B2C sign-up and sign-in policy using the steps outlined in this resource, I have successfully created custom Sign-Up and Sign-In pages. However, my next goal is to make the sign-up page dynamic by passing ...

Maintain the horizontal alignment of CSS floats

What causes the div on the right to float higher than the two divs on the left? How can I ensure they are all aligned at the top? HTML <header> <div class="nav" style="width:100%;border:#900 thin solid;"> <ul id='nav-left' ...

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

How can you display a set of components in React using TypeScript?

I'm currently working on rendering an array of JSX Components. I've identified two possible methods to achieve this. Method one (current approach): Create the array as an object type that stores the component properties and then build the JSX co ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

Retrieve information from a row by clicking on it, then present it in a dialog box for editing

I'm working on a project using Angularjs to retrieve data from a table row when it's clicked and then display the data in an editable dialog box. I need help with implementing this feature. Here is my current progress: <table> ...

I am looking to retrieve the values entered in a textbox from an HTML document and then post them using a JSON file in Node.js when the submit button is

Here is the JavaScript code I have written: $(document).ready(function(){ $('form').on('submit', function(){ var email = $("form input[type=text][name=emails]").val(); var todo = {email: email.val(), ...

AngularJS does not recognize a dynamically created array when using ng-include with ng-repeat

Issue with ng-repeat Directive I have encountered a problem where the ng-repeat directive does not track the addition of a new array, specifically 'options'. This issue arises when the directive is used within a template displayed using ng-dialo ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Dealing with $http errors: differentiating between user being offline and other error types

I have a straightforward contact form that Angular submits via AJAX to my application on Google App Engine. (A POST handler uses the send_mail function to email the website owner). Here is the client-side code snippet: $http.post('', jQuery.para ...

The functionality of Express JS routers is experiencing issues

As I delved into learning nodejs and express, I decided to create a basic router. Initially, everything seemed to be working fine, but upon reopening the project, I encountered an issue. var express = require('express'); var app = express(); var ...