The variable $myform.textinput.$isvalid is unexpectedly true

For the form to be considered valid, at least one item must be added to stuff[]. When a user enters a value into the text box and clicks "add", the value is then added to stuff[]. Only when a value has been added to stuff[] should the submit button be enabled. However, if the user simply types something into the text box without clicking add, resulting in nothing in stuff[], the form is still considered valid and the submit button is enabled.

<form ng-app="myApp" ng-controller="myCtrl" name="myForm" ng-submit="submit()" novalidate>
    <div ng-repeat="things in stuff">
        <table><tr><td>{{things}}</td></tr></table>
    </div>

    <input type="text" name="app" ng-model="input" ng-required="!stuff[0]" />

    <button ng-disabled="!input" ng-click="add()">
        <span> add</span>
    </button>

    <input type="submit" value="Submit" ng-disabled="myForm.$invalid" />

    <script>
        angular.module('myApp', []).controller('myCtrl', function ($scope) {
            $scope.stuff = [];
            $scope.input = null;

            $scope.add = function () {
                var l = $scope.stuff.length;
                $scope.stuff[l] = $scope.input;              
                $scope.input = null; 
            };
            $scope.submit = function () {};            
        });
    </script>
</form>

Answer №1

[UPDATE] In response to your inquiry: The condition !stuff[0] evaluates to TRUE only when the array is empty, and FALSE otherwise. When it is TRUE, input is required to make the form 'initially' invalid. Upon entering text into the input field, the requirement is satisfied, thus making the form valid and enabling the submission of the form. It is important to note that this condition pertains to the array contents, not the act of adding something to the array itself.

To address this issue, consider implementing a conditional check based on stuff.length, as suggested in my subsequent answer. While this approach may not render the form invalid (a separate condition can be used for this purpose), it will effectively disable the submit button until an item is added to the array. [/UPDATE]

I am puzzled by the presence of ng-required in this context, as the objective seems to be disabling the submit button rather than enforcing input requirements on the text box.

An alternative implementation could look like this:

<input type="text" name="app" ng-model="input"/>

<button ng-disabled="!input" ng-click="add()">
    <span> add</span>
</button>

<input type="submit" value="Submit" ng-disabled="stuff.length == 0" />

This modification will deactivate the submit button if the stuff array is empty.

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

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

The React Apexchart fails to correctly adjust its height based on its parent container when set to 100%

Currently, I am working with react-apexcharts and facing an issue where I am trying to set the height of the chart to be 100% of its parent element. However, instead of taking the height from its parent, it is only showing a minimum height of 445px. Even a ...

The height returned by $.height is always zero when using colorbox

I am adjusting the height of td to be auto and then trying to transfer that height value to another td within a colorbox. Below is my HTML structure: <tr> <td class="heading1" id="mhheading"><?php echo $this->translate("Medical Histo ...

Can someone guide me on how to call a child function from the parent component by utilizing bindings in AngularJS?

I am working on a parent component that includes a child component. <child-component></child-component> Within the child component, there is a function: $ctrl.alertMe = function() { alert('me'); } I am trying to figure out how ...

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

Encountering issues with npm installation in AngularJS

I am new to angular js and just started learning it. However, I encountered an error when running the npm install command. npm install> [email protected] install C:\Users\A626262\WebstormProjects\FirstJsApp\node_modules&bso ...

"Exploring the power of Supertest in NodeJS to interact with session

While conducting tests on my Node.js application using supertest, I encountered an issue with accessing the session object in my controller. This object requires certain data to be present in order for a valid request to be made. Controller // ch ...

When the jQuery AJAX call is successful, the function is returned as data

Here is my implementation using codeigniter flashdata with a jQuery AJAX call: <script type="application/javascript"> var res_no = '<?php echo $this->session->flashdata('res_no'); ?>'; var res_new = '<?php ec ...

Transforming three items into an array with multiple dimensions

There are 3 unique objects that hold data regarding SVG icons from FontAwesome. Each object follows the same structure, but the key difference lies in the value of the prefix property. The first object utilizes fab as its prefix, the second uses far, and t ...

Link clicking does not trigger URL routing properly

I've been tasked with updating our web application, and I'm facing a challenge that I need help with. My boss wants users to be able to click on a link in an email and have the internal company web app directly navigate to a specific page indicat ...

Modifying the $scope within a controller

I need to update the $scope within the controller based on the object that is being clicked. The current code looks like this: var blogApp = angular.module('blogApp', ['ngSanitize', 'ngRoute']); blogApp.controller('blog ...

Exploring the Dynamics of AngularJS: Leveraging ng-repeat and ng-show

Recently, I came across this code snippet: <div class="map" ng-controller="DealerMarkerListCtrl"> <a ng-click="showdetails=!showdetails" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker.left}}px;top:{{marker.top}}px" ng-rep ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Steps to avoid reinitializing the component upon changing routes in an Angular 9 component

In my component, the width of a chart is stored in a variable (because I can't use style for d3). However, every time the route changes, all variables in this class component become undefined. I have tried using ngIf, services (which also become unde ...

Issue: ASSERTION ERROR: token must be declared [Expecting => null is not undefined <=Actual]

I encountered an error while working on my project. The only special thing I did was use oidc(openId) for authentication. I made some changes to the bootstrap project and now the first component that is running is the home-main component, which includes t ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

Tips for efficiently sharing or waiting for data between files in Mocha

Imagine having a file called "main.js". It includes the following: const User = require('../models/user'); describe('Testing', () => { before(async function(){ await User.deleteMany({}); }); require('./users ...

Unable to load an object using Three.js due to a formal parameter that is missing

My goal is to utilize Three.js (OGL + JavaScript) to load an object from a file. I have a functional example that renders some basic elements, but when attempting to load an object using JSONLoader.load(...), Firefox's console displays an error: Synt ...

Clicking on a JQuery element triggers an AJAX function, although the outcome is not aligned with the intended

Instead of using a fiddle for this task, I decided to work on it online since my knowledge of fiddles is limited. However, after multiple attempts and hours spent rewriting the code, I still can't get it right. The issue at hand requires that when cl ...