AngularJS disregards the disabled attribute when submitting a form

One of the challenges I faced was creating a directive that disables inputs on boxes unless they are double-clicked as "active". Despite my efforts, AngularJS still passed disabled inputs to a scope function.

Simplistic input HTML:

 <div class="selectable-boxes" toggle-inputs>
        <div class="box selected">
            <div class="form-container">
                <div class="form-group">
                    <input type="text" placeholder="First" name="f1" data-ng-model="fields.information.f1"></div>
                ...

All labeled as f1, f2, f3..

Custom Directive:

app.directive( 'toggleInputs', function() {
    return {
        link: function(Scope, element, attrs) {
            var $element = element;

            $element.find('.box').bind('dblclick', function () {
                $element.find('.box').removeClass('selected');
                $(this).addClass('selected');
                toggleInputDisabled();
            });

            function toggleInputDisabled() {
                $element.find('.box').each(function () {
                    $(this).find(':input').attr('disabled', !$(this).hasClass('selected')).attr('data-ng-disabled', 'isDisabled');
                });
            }

            toggleInputDisabled();
        }
    };
});

The directive does its job by disabling fields and adding ng-disabled="'isDisabled' with $scope.isDisabled = true;. Yet, these values persist in being included in a $scope function. Why is this happening?

Object {f1: "1", f2: "2", f3: "3", f10: "4", f11: "5"…}

Answer №1

If you want to make your code more readable and efficient, consider using ng-disabled instead of a complicated jQuery expression:

NG Disabled

The attribute is already present on the input box and can be toggled by the code.

By utilizing true angular functionality, all disabling tasks can be handled seamlessly without the need for additional code or potential issues from post-fixing attributes.

Check out this Plunkr example based on my suggestion:

Plunkr example

In the HTML section:

<div class="form-group">
    <input type="text" placeholder="First" name="f1" 
    data-ng-model="fields.information.f1" ng-show="!hideem" ng-disabled="disabled">
</div>

Here are the two control checkboxes:

Disable <input type="checkbox" ng-model="disabled" name="diablethem" id="disablethem"/>

Hide <input type="checkbox" ng-model="hideem" name="hideem" id="hideem"/>

Make sure to initialize your items as needed:

$scope.disabled=false;
$scope.hideem= false;

Answer №2

To ensure the attribute is properly updated, remember to recompile the element in jQuery after making changes:

function toggleInputDisabled() {
    $element.find('.box').each(function () {
        $(this).find(':input')
            .attr('disabled', !$(this).hasClass('selected'))
            .attr('data-ng-disabled', 'isDisabled');
        });
    }
    $compile($element)(scope);
}

Include the necessary dependency:

app.directive( 'toggleInputs', function($compile) { … }

Answer №3

I encountered a dilemma and found a creative workaround to tackle it. The crux of the issue appears to lie in the ng-model element, based on prior comments, as it establishes a binding that is challenging to eliminate while still needing it for ng-click="function(fields)".

To address this obstacle, I devised a directive that adjusts the scope by introducing an additional 'replaced' parameter within the object tree I am utilizing. Subsequently, I verify its existence and leverage these new values; however, a complication arose in this process.

Eventually, in order to identify these fresh values effectively, I resorted to employing a setTimeout(function() { }, 100); within the controller function since they remained elusive otherwise.

app.directive( 'buttonClick', function() {
  return {
    link: function(scope, element, attrs) {
      element.bind('click', function() {
          scope.fields.information.replaced = {};

          var i = 0;

          $('.selectable-boxes .box.selected input').each(function() {
                scope.fields.information.replaced['f' + i] = $(this).val();
                i++;
          });

          scope.$apply();
      });
    }
  };
});

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

Steps to sending an email to an administrator using PHP and jQuery

I am looking for a way to send a notification email to my site admin whenever a user submits a request via a form. Currently, I have the following code that is supposed to link to a PHP file on my server to handle the email sending: $("#modelform").submit ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Start by executing the function and then proceed to upload a static file

Here is the code I am working with: var express = require('express'), app = express(); app.use(express.static(__dirname + '/static')); app.get('/', function(req, res) { //??? }); app.listen(80); I need to first ex ...

Opting for CSS3 transitions over jQuery animate

Currently, I am working on animating a block of HTML that involves fading in (opacity) and slightly moving from the left (margin-left)... $('.latest-stats').delay(1000).animate({ opacity: 1, marginLeft: '55px' }, 1000, function () { ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Creating dynamic classes in VueJS

After carefully reviewing the documentation, I am puzzled about how to modify a class. My component's data is structured as follows: props: [ 'm_c_id', 'recipient_id', 'sender_id', 'userId' ], If sende ...

Creating a navbar that sticks to the top of the page

I've been working on some code to create a sticky navbar that remains fixed as I scroll down, but unfortunately, it's not working. I suspect the issue might lie in the CSS, as the HTML and javascript seem fine. Interestingly, this same code has w ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

What is the process for uploading a series of images through the fetch API?

I am attempting to use my custom API (Node JavaScript) to upload an array of images. My goal is to save the file names to my database, and the uploading process itself is functioning correctly (the middleware I created for uploading works perfectly as I ha ...

What could be causing htmlparser2 in Node.js to add extra nodes during document parsing?

Seeking to extract the HTML content of a webpage using node so I can process its DOM to create something unrelated. It's crucial to accurately obtain the DOM representation from the HTML in order to properly process it. Utilizing htmlparser2 for this ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Encountering a MODULE NOT FOUND error when using express.js

const express = require("express"); const app = express(); const path = require("path"); app.use(express.static(staticPath)); let staticPath=path.join(__dirname, ".."); There seems to be an error in these lines of ...

What sets apart npm correlation-id from uuid?

Can you please explain the distinction between the uuid and correlation-id npm packages? It seems that correlation-id actually utilizes the uuid package internally.. When would you recommend using correlation-id over uuid? Important: I am not utilizing ...

Simulating a traditional table scroll function on a window using virtualization

I am currently attempting to incorporate a virtualized table in react using react–virtualized, but I am facing issues with the rendering of the table. I am seeking to understand the root cause for this problem as well as find solutions for other overlapp ...

The Stripe technique appears to not be classified as a Function type

I added stripe to my project using npm install --save stripe, but when I include the following line const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);, I receive a warning stating that the stripe method expression is not of Function ...

Tips for sending an array of data from the client to req.body in an axios request

I am facing an issue with sending user data collected from the front end via an ajax call to an axios post request in the back end. The parameters I need to pass include arrays of data, but when I check the req.body in the backend using console.log(), I no ...

Retrieve data from Ionic storage

Need help with Ionic storage value retrieval. Why is GET2 executing before storage.get? My brain needs a tune-up, please assist. public storageGet(key: string){ var uid = 0; this.storage.get(key).then((val) => { console.log('GET1: ' + key + ...

Investigating the variety of HTTP 206 responses pertaining to video content

Currently, I am utilizing Amazon CloudFront to serve HTML5 videos. These videos are being requested through HTTP range requests and the expected responses are often in the form of HTTP 206 Partial Content. I have a requirement where I want to log the requ ...

Gather data on webview requests and their corresponding responses

In my app, I am developing a feature that allows users to browse the web using a webview element. <webview src='user-generated'></webview> I am trying to find a way to capture all requests and responses generated during this process ...