1

I am using the following code to reset a form field using a checkbox with AngularJS.

<input type="text" ng-model="data.test" ng-disabled="data.check">

<input type="checkbox" 
ng-change="data.test = data.check ? '' : data.test"
ng-model="data.check" 
value="one">

How would I use this code to reset multiple form fields?

Thanks,

John

2
  • you want to reset the form fields when the checkbox is checked? Commented Sep 5, 2016 at 18:04
  • yes, the code works above but just on a single field. Commented Sep 5, 2016 at 18:08

2 Answers 2

1

Store the data in separate array and validator in another variable

<input type="text" ng-model="data.test" ng-disabled="clear.check">
<input type="text" ng-model="data.test_another" ng-disabled="clear.check">

<input type="checkbox" ng-change="data = clear.check ? {} : data"
ng-model="clear.check" value="one">

Once you want to reset the form data, you can directly assign empty array set to form data array

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this code and it did not work. Was there something else I needed to add other than the above?
its working fine for me, check my plunker plnkr.co/edit/wrV9vZMdFqtlqtvLxWAA
It works! Not sure what I was doing wrong but it's working fine now.
Only problem I have now is that checked="checked" does not work on the checkbox. It looks like it's ng-model="clear.check" causing the problem?
0

You can use $setPristine() for resetting the field state.

HTML:

<form name="myForm">

    <input type="text" ng-model="data.test" ng-disabled="data.check">
    <input type="text" ng-model="data.test2" ng-disabled="data.check">
    <input type="checkbox" 
    ng-change="reset()"
    ng-model="data.check" 
    value="one">
</form>

JS:

$scope.resetForm = function() {
    $scope.data = {
        "test": "",
        "test2": ""
    };
    // 'myForm' is the name of the <form> tag.
    $scope.myForm.$setPristine();
}

1 Comment

I tried your code and get a - Can't find variable: $scope error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.