Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text.

https://i.sstatic.net/iTKoo.jpg

I want the validation message to appear after the checkbox text. I specifically need to implement this within the directive without making changes to the controller or template. How can I achieve this?

    app.directive('validate', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel', 

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;          
              }
              ngModel.$setValidity('validation', false);

              scope.directive_function= function(){
                alert("directive function");
              }

              ngModel.$parsers.push(function(val){
                if(val==true){
                  ngModel.$setValidity('validation', true);
                  var elemento_eliminar=(angular.element((document.getElementById('errorchec' ))));
                  elemento_eliminar.remove();
                }else{
                 ngModel.$setValidity('validation', false);
                 var newDirective = angular.element('<div id="errorchec" class="span_wrong" style="margin-top:5px; color:red">'+"must be required"+'</div>');
                element.after(newDirective);
                }
              })
           }


        };
    });

http://jsfiddle.net/venzoub4/

Answer №1

To properly align the validation, you simply need to apply the position:absolute CSS property.

<div id="errorchec" class="span_wrong" 
style="position: absolute;margin-top:5px;color:red;">must be required</div>

Check out the demo here

Answer №2

If you want it to show up beside the input field, you can include display: inline-block in the div tag or just use a span element.

<div id="errorchec" class="span_wrong" 
     style="margin-top:5px; color:red; display: inline-block;">

Answer №3

<label><input type="checkbox"  ng-model="check1"  value='value1' validate />value1</label>

Within your HTML, there is a <label> containing an <input> and the text value1. The directive points to the input element; although the error <div> is placed correctly after the input, it should actually be outside the label.

To achieve this positioning, you need to target the parent element using .parent.

element.parent().after(newDirective);

http://jsfiddle.net/b1qnny6a/

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

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend... public class ScoreModel { public string Subject { get; set; } public float Score { get; set; } ...

Constructing links for API and view in Flask

In the process of developing a flask application with angularjs frontend, I have encountered an issue where templates are not being rendered from Flask yet, as they are currently delivered as static files. The API endpoint in question is shown below: @rou ...

Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files. To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing ...

How to retrieve values/keys from a JSON object dynamically in JavaScript without relying on fixed key names

shoppingCart = { "Items": 3, "Item": { "iPhone 11 Pro": { "productId": 788, "url": "http://website.com/phone_iphone11pro.html", "price": 999.99 }, "Bose Noise Cancelling Headphones": { ...

Insert data into a function property in AngularJS

Here is the custom function I have created: var _loadNieuws = function (url) { switch (url) { case 'example1': _nieuws = EXAMPLE1_NIEUWS; break; case 'example2': _nieu ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

Create a placeholder DOM element in Jasmine for testing AngularJS

My journey with Jasmine has just begun, and I've encountered a strange issue. While testing a function that involves DOM manipulation along with another function call, Jasmine throws an error stating that elem.className is not a constructor. Here&apos ...

What is the best way to assign a PHP array to an Angular variable?

Currently, I am working on a web development project where PHP is being used to retrieve match information from the database and store it in an array. My goal now is to utilize Angular to display this data. Can you suggest how I can effectively transfer ...

The height of the iframe with the id 'iframe' is not functioning as expected

I am trying to set the iFrame's height to 80% and have an advertisement take up the remaining 20%. Code <!DOCTYPE html> <html lang="en"> <head> </head> <body> <iframe id="iframe" src="xxxxxx" style="border: ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

Executing server-side method with jQuery in .Net 1.1

Currently, I am utilizing .net1.1 and attempting to invoke a server-side method using jQuery upon clicking the browser's Close button. However, my code does not seem to be functioning correctly. I have provided my code below for reference. Can anyone ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

What is the best approach for extracting functions from express routes for unit testing?

I have a JavaScript controller containing some exported routes. I am interested in accessing the functions used within these routes for unit testing purposes. While many blogs suggest creating actual HTTP requests to test express routes, I consider this t ...

Guide on sending a JSON response from an API endpoint in Next.js

As I work on developing a small REST API for a Next.js application, I encountered an interesting issue. Initially, when I placed my route.ts file in the directory structure rootDir -> app -> api -> hello -> route.ts with the following code snip ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

JavaScript function to convert a string of characters into a readable time format

Is there a way to input a string in an 'input type="time"' field in my HTML code? <label class="item item-input"> <span class="input-label">Departure Time </span> <input type="time" ng-model="heur ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

What sets apart posting data through an HTML form submission from posting data through an Ajax request?

Recently, I've encountered an issue with my Post API. When calling it through AJAX, the user parameter is received but the StreamReader returns empty. [HttpPost] [Route("getUserBankList")] public IHttpActionResult getUserBankList(UserProfile ...