Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need to fill in. These properties are dynamic and the number of fields varies since they are within a loop.

My objective is to disable the submit button at the bottom of the page if any input field in either set of data is left empty. This functionality should also be compatible with Internet Explorer 9 where the 'required' tag is not supported.

Here are the solutions I've tried so far:

  • Using the required tag: Unfortunately, this doesn't work on IE9 and even in Google Chrome, as the form still submits when fields are empty (even after including form tags).

  • Implementing Ng-show on the submit form: I attempted to check if userInput is empty, but this approach did not yield the desired outcome.

  • You might wonder why I don't just validate these properties in my controller during the submit process. While that would be ideal, accessing this dynamic data directly in the controller poses challenges. Therefore, I am seeking a solution that can address this issue with minimal intervention in the controller.

Code:

<!--Start wrapper!-->
<div class="wrapper">
  <div ng-repeat="(code, program) in data.old.heat">
    <div class="row" ng-repeat="(componentId, component) in program">  
      <div class="inputForm">
        <!--This field may not be left empty!-->
        <input type="text" class="form" ng-model="component.userInput">
      </div>
    </div>
  </div>

  <div ng-repeat="(code, program) in data.old.cold">
    <div class="row" ng-repeat="(componentId, component) in program">
      <div class="inputForm">
        <!--This field may not be left empty!-->
        <input type="text" class="form" ng-model="component.userInput">
      </div>
    </div>
  </div> 
</div>
<!--End of wrapper !-->

<div class="submitPanel">
  <button ng-click="submit()">Submit</button>
</div>

Answer №1

Check this out : https://jsfiddle.net/CLEAN_SMITH/fbxcnzr8/

function validateForm(){
var input1 = document.getElementById('input').value;

if (input1.length > 0){
    alert("Validation successful");
    return true;
}
alert("Validation failed");
return false;
}

Answer №2

Not specific to Angular, but one way to determine if a field has characters is by using jQuery.

Here's an example with HTML:

<div class="submitPanel">
  <button class="submit-btn" ng-click="submit()">Submit</button>
</div>

And here's some jQuery code:

$('#form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('.submit-btn').addClass('hide');
    }
});

Lastly, we have some CSS:

.hide {
    display: none;
}

Answer №3

If you're looking for solutions, I have a couple of options that may work for you. Both involve using the ng-disabled directive in your AngularJS code.

One option is to add the ng-disabled attribute directly to the button element and call a function on the scope that checks if all values are provided. For example: ng-disabled="checkInputs()".

Alternatively,

You can surround all your input elements with a form, give it a name like name=form, and set the required attribute on each input. (Note: for compatibility with IE9, consider using ng-required="true").

Then you can disable the button based on the validity of the form: ng-disabled="!form.$valid".

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

Ways to adjust the color of individual elements within an array

I am currently working on developing a sorting Visualizer using React. My focus right now is on implementing BubbleSort. Below is the structure of my program: https://i.sstatic.net/3TKqe.png Below is the code snippet I have written for this task: class S ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

Using Regular expressions in JavaScript to eliminate content between two HTML comment tags

I am currently dealing with two HTML comments in this format: <!--Delete--> Blah blah blah blah <!--Delete--> I need to remove these comments, along with any characters and newlines. I am utilizing JavaScript and Grunt for this replacement ta ...

I need to press the button two times to successfully submit

I am experiencing a remote validation issue. When I click on the submit button without focusing on the text box, it triggers a remote ajax call for validation. However, when I press the submit button a second time, the form gets submitted. On the same cl ...

Automatically preselect the checkbox inputs with the API and update their status when they are interacted with

Hello fellow developer, I trust you are doing well. I am looking to have the checkboxes automatically checked based on data from the API and update their status when interacted with. I've tried different approaches but haven't found the right sol ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Sending a multi-dimensional array to the server using PHP via POST

Similar Question: multi-dimensional array post from form I am looking to transfer data from the client to the PHP server using jQuery's $.post() method. Once the data reaches the server, I want the $_POST['myList'] variable to be in one ...

Issue with overlapping sticky dropdown and sticky navigation in Bootstrap 4

My issue revolves around getting the dropdown button menu to display in front of the vertical menu. When I click on the dropdown, the vertical (blue) menu takes precedence. This problem arose suddenly after applying the sticky-top class to both menus. Whil ...

What is the best way to explore JavaScript text using Firebug?

The search function (magnifying glass) located at the top-right hand corner of Firebug does not have the capability to search within JavaScript blocks. For instance, if I have the following code snippet: <script type="text/javascript"> var fooBa ...

Is it possible to manipulate the attribute of an object using Object.defineProperty when a value is passed as a function parameter?

As I delve into understanding reactivity in Vue, the concept of how reactivity is achieved when passing a value as a function parameter perplexes me. //here is the actual code snippet var obj = {a: 'aa'} function reactive(obj, key, value) { ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Trouble retrieving data (React-redux)

Greetings! I am currently working on a project involving the Spotify API and attempting to retrieve new releases. While the data is successfully passed down to the reducer, I encounter an issue when calling the fetch action in my App component. When I try ...

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...

Executing the command "node <app name>" does not result in any action

I am experiencing an issue with my bot app called "vgen.js". When I run the command "node vgen", the prompt/directory disappears and the cursor just blinks on the far left of the screen. I have been following instructions from a tutorial found here: https ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...