Reinitializing AngularJS form controls

Check out this codepen example:

http://codepen.io/anon/pen/EjKqbW

I'm trying to reset the form elements when the user clicks on "Reset". The div elements f1,f2,f3 should be hidden and the searchText box cleared. However, the reset button is not triggering. Could it be because AngularJS does not allow multiple submit buttons in a form?

Is there a way to reset the form elements as specified when "Reset" is clicked?

Source code snippet:

<html>
  <head>
    <title>AngularJS test</title>
  </head>
  <body ng-app ng-controller="TestCtrl">

    <form ng-submit="submit()">

       <div style="display:none" id="notFound">Not Found</div>

       <div style="display:none" id="f1"></div>
       <div style="display:none" id="f2"></div>
       <div style="display:none" id="f3"></div>

          <input id="searchText" type=text/>

    <input type="submit" ng-click="submit" value="Submit">

    <input type="submit" ng-click="reset" value="Reset">

            </form>

     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

</body>
</html>

function TestCtrl($scope , $http) {

  $scope.reset = function() {

      $("#f1").css('display' , 'none');
      $("#f2").css('display' , 'none');
      $("#f3").css('display' , 'none');

        $("#searchText").text('');
  }

  $scope.submit = function() {

    $http.get('').
    success(function(data, status, headers, config) {

     // this callback will be called asynchronously
    // when the response is available

      $("#f1").text('test');
      $("#f1").css('display' , 'block');

      $("#f2").text('test');
      $("#f2").css('display' , 'block');

      $("#f3").text('test');
      $("#f3").css('display' , 'block');

  }).
  error(function(data, status, headers, config) {

       $("#notFound").css('display' , 'block');
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });



  }




}

Answer №1

It is not recommended to use both ng-click on buttons and ng-submit on forms in Angular. This can cause conflicts as both functions will be called simultaneously.

Please refer to the warning on this topic: https://code.angularjs.org/1.3.15/docs/api/ng/directive/ngSubmit

When using ng-submit, it triggers whenever an input of type "submit" is clicked. To avoid issues, make sure the reset button is of type "button".

Additionally, ensure that ng-click="reset" is written as ng-click="reset()"

Here is a working example: http://codepen.io/anon/pen/NqNQQq

UPDATE: In response to @isherwood's comments, it is important to note that utilizing jQuery within an Angular controller to manipulate HTML is not recommended. Consider exploring directives and using angular.element (only when absolutely necessary, which should be avoided if possible). I have updated the example to eliminate the use of jquery.

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

How can I send a current variable through PHP?

I have a pressing deadline and I need some guidance before moving forward. Can someone please advise if what I'm attempting is feasible or if there's a quicker solution? I encountered some problems with an accordion menu, so as a temporary fix, ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

What is the most concise way to align one table row in the middle and another at the top?

Is there a way to align different rows in a table vertically with minimal code? I have a table with 3 rows, and I want the first two rows to be aligned vertically to the top, while the third row should be vertically aligned to the middle. If I try to def ...

Invoke jQuery within a nested context once more in the jQuery method sequence

Is it possible to do something like this? jQuery(selector).jQuery(subselector).command(....) Here is the current code snippet: $(' .species') .filter(function () { return !$(this).data('hidden_code_ready'); } .wrapInner('<spa ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...

Dropdown navigation with CSS

It seems like there's a simple oversight on my end... The drop-down menu I created is causing the main navigation bar to expand. You can view the page I'm working on by following this link. The issue occurs with the navigation below the App butto ...

What is the best way to include a substantial amount of HTML in a Vue.js template?

As a newcomer to Vue.js, I have a question regarding the rendering of a large amount of HTML in a Vue.js template. When I include around 500 lines of plain HTML code in my template and run npm run dev the compiling process becomes extremely slow or d ...

An unusual outcome occurred while attempting to duplicate the text

After copying the letter A, I noticed that an empty string is being logged to the console instead of the expected A. However, when I paste, the console does successfully log the letter A. document.addEventListener('copy', handler); document ...

Having difficulty getting a basic code to work: ajax method ($.post) with MySQL is not

I am facing an issue with this code not functioning properly. I want to display the result of a MySQL query without sending any data using my simple Ajax code. $('.myClass').on('click',function(){ $.post('resultAll.php'); ...

Access-Control-Allow-Origin header not being sent by ExpressJS

In the midst of my project, I find myself needing an angular web application to connect with a node/express backend. Despite trying to implement Cors for this purpose, the express server refuses to send the Access-Control-Allow-Origin header. I am perplexe ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Display flex behaving unexpectedly in Chrome and Safari browsers

I utilized flexbox properties to achieve this layout for my section: While it functions smoothly in Chrome, I noticed some disparities when viewing in Firefox and Safari. This is how it appears in Chrome: In Firefox, I'm encountering difficulty in ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Ways to invoke a function in Angular2 when the Boolean condition is met

Within my component class, I have implemented a popup function along with a Boolean flag that returns true or false based on specified conditions. In the template class, I want the popup function to be triggered when the flag becomes true, displaying a pop ...

What is the best way to handle exceptions when dealing with MongoDB?

Issue Encountering a problem where the try block fails to capture errors when utilized within the MongoClient's connect function in MongoDB. System Details Operating System: Linux (Mint, Tessa) Node.js Version: v10.16.0 (utilizing ES6 with nodem ...