AngularJS - submit form with checkboxes via ajax - javascript

I have a form with checkboxes and other input fields.
The data-ns-form directive is used for submitting form data via ajax. The controller for this form is UserController.
HTML
<div ng-controller="UserController">
<form data-ns-form="formData">
Full Name : <input type="text" name="fullname" ng-model="formData.fullname" />
Favourite Beverage :
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[0]" value="coffee"> Coffee
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[1]" value="tea"> Tea
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[2]" value="colddrinks"> Cold Drinks
</label>
<button type="submit"> Send </button>
</form>
</div>
Controller
app.controller('UserController', function($scope){
$scope.formData = {fullname : '', beverages : []};
});
Directive
app.directive('nsForm', function(){
return {
restrict : "A",
scope: {
formData : "=nsForm"
},
link : function(scope, iElem, iAttr) {
$(iElem).on('submit', function(e) {
e.preventDefault();
console.log("FORM DATA");
console.log(scope.formData);
});
}
}
});
A little description
When I submit the form I get boolean TRUE for checked checkboxes, but instead I want the value inside the value attirbute. For instance, If I checked 'coffee' and 'Cold Drinks', I get beverages=[true,false,true], but what do I want is beverages['coffee','colddrink'].
What is the AngularJS way of doing it?
And Also.
Is there any preferred way of submitting form in AngularJS instead of creating directives myself ?

I don't see any reason for the "name" attribute here. You need to use ng-click with a function to save your data - and that should be taken care of by a service. There's a lot you can do with angular...search the docs for anything you're doing (see checkboxes in the docs, for example).
Live demo here (click).
<div ng-controller="UserController">
Favourite Beverage :
<label>
<input type="checkbox" ng-model="formData.beverages[0]" ng-true-value="coffee">Coffee
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[1]" ng-true-value="tea">Tea
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[2]" ng-true-value="colddrinks">Cold Drinks
</label>
<button ng-click="save()"> Send </button>
</div>
js:
var app = angular.module('myApp', []);
app.factory('myService', function($http) {
var myService = {
save: function(data) {
//your ajax call here
console.log(data);
}
};
return myService;
});
app.controller('UserController', function($scope, myService) {
$scope.formData = {};
$scope.formData.beverages = [];
$scope.save = function() {
myService.save($scope.formData);
};
});
Also, you should probably have all of your data (the drink values, for example) in your javascript rather than the html, then bind it to the page. Or in the database, then into js, then onto the page. That all depends on how dynamic your information needs to be - just be sure to think ahead.

Related

Need to get value of the radio button and pass it to the backend using HTML and angularJS,and the data displayed in the frontend is a list

//This is my HTML code wherein am returning a list from backend.
<ul>
<li ng-repeat=" opt in bcfList1 track by $index" > <input type="radio" name="buildid" id="buildid" ng-model = $parent.selected ng-value="bcfList1" required>
{{ opt }}
</li>
</ul>
//This is my controller.js program
$scope.getDetails =function(data){
var id=data.id;
$('#addNode3').modal('show');
UpgradeService.getDataById(id).then(function(data){
if(data!=null){
$scope.List1=data.BUILDNUMBER;
}
});
}
I need to get the string value that'll be listed in front of the radio button. So once I click on radio button it should send that value to the controller.js
By using ng-model I need a solution.
Help me out!!
You need to add ng-change to your input fields with a call to that function. Here is a quick demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.b = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$scope.getDetails = function(index) {
console.log("sending data", index,$scope.selected);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="a in b track by $index">
<input type="radio" ng-model="$parent.selected" ng-value="a" ng-change="getDetails($index)" /> {{a}}
</div>
</div>
If I understand correctly, you need to gather which input type radio was clicked in controller and send this information to backend.
ng-model directive is very good approach here and you can use it just like so:
html
<label>
One
<input type="radio" value="one" ng-model="radio">
</label>
<label>
Two
<input type="radio" value="two" ng-model="radio">
</label>
<br><br>{{ radio }}<br>
JS
app.controller('MainCtrl', function($scope) {
$scope.radio = '';
$scope.consoleLogRadio = function() {
console.log($scope.radio);
}
});
Take a look at plunker example

AngularJS process form on form click

I'm trying to submit a form when user clicks on any part of the form, and then process it using AnglujarJS. Here's how I tried doing it:
<form ng-click="submit()" ng-app="MyApp" ng-controller="MyCtr">
<input type="text" ng-model="my_val" name="my_val" value="0" style="display: none"/>
</form>
var app = angular.module('MyApp', []);
app.controller('MyCtr', function($scope) {
$scope.submit = function() {
$scope.my_val; // This is undefined
});
};
});
The problem is that $scope does not have form values. If I replace ng-click with ng-submit, the values are present, but I don't want to submit form by clicking on a submit button.
You need to declare and set to 0 $scope.my_valoutside of submit function and also ij Js code there are unnecessary closed brackets check that as well.
var app = angular.module('MyApp', []);
app.controller('MyCtr', function($scope) {
$scope.my_val="0";
$scope.submit = function() {
$scope.fromvalue.my_val
console.log($scope.fromvalue.my_val.$viewValue);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="fromvalue" ng-click="submit()" ng-app="MyApp" ng-controller="MyCtr">
<input type="text" ng-model="my_val" name="my_val" value="0"/>
</form>

Get HTML element data in AngularJS script

I am new to AngularJS and trying to design a page which will have two text fields and two radio buttons.
First text field is for current address, followed by radio buttons(one for Yes and second for No), and last component would be permanent address text field. First, user will enter the value in current address text field, after that if user selects yes radio button then it should copy the data from current address to permanent address text field, if user selects No then it should do nothing. Below is the sample code I have written:
*<input type="text" name="cAddress" ng-model="cAddress" required/>
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" required/>*
Below is the script code inside controller:
$scope.copyAddress = function(flag) {
if(flag) {
$scope.pAddress = $scope.cAddress;
}
};
when I tried to print $scope.cAddress and $scope.pAddress values in console then it displayed undefined. Even $scope does not have cAddress and pAddress.
Therefore, the main problem is that I am not getting element data inside AngularJS controller
Please find plunker url:
http://plnkr.co/edit/Ub2VEn01HxwDpnCg4tLi?p=preview
Click on Next to navigate to Second tab, there you will find the yes and no radio button to copy the data.
I have minized the code, please look into it. To understand the flow, you can read the README file.
http://plnkr.co/edit/TzJsZIRxAyTuFdCXLFFV?p=preview
Try using another scope object.
That is, create a scope object and add property to it for each input like,
$scope.myObject = {}; // Empty scope variable
$scope.myObject.cAddress = ""; // initialize your model for the input.
And now you should use this variable for your input.
<input type="text" name="cAddress" ng-model="myObject.cAddress" required/>
Try this. It may help you.
Html code:
<body ng-controller='Maincontroller'>
<input type="text" name="cAddress" ng-model="cAddress" />
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" />
</body>
Controller code:
var app = angular.module('main', []);
app.controller('Maincontroller', ["$scope",
function($scope) {
$scope.copyAddress = function(flag) {
if (flag) {
$scope.address1 = $scope.address;
} else {
$scope.address1 = "";
}
};
}
]);

update radio value in angularjs service

I have a list of radio button values in ControllerA, printed in the view with ng-repeat. The list comes from a service. Now I want to check which radio button is selected in ControllerB.
How do I get the current selected value?
Do I need to add a $watch function in ControllerA and update the service that way?
Or is there a different way of basically binding a variable from a controller to variable in a service?
There's no need to set a $watch; it's all about sharing state between controllers.
Javascript
var app = angular.module('app', []);
app.factory('myState', function() {
// For this example I'm just returning the state directly, but it can also
// be returned from some function or even some backend api. Just remember
// that factories (services/providers) are singletons and will point always
// to the same instance within your app.
return {
chickenEgg: 'egg'
};
});
app.controller('ControllerA', function($scope, myState) {
$scope.formData = myState;
});
app.controller('ControllerB', function($scope, myState) {
$scope.result = myState;
});
Html
<div ng-controller="ControllerA">
<h2>ControllerA</h2>
<form class="form">
<label>Chicken or the Egg?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="chicken" ng-model="formData.chickenEgg">Chicken
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="egg" ng-model="formData.chickenEgg">Egg
</label>
</div>
</div>
</form>
</div>
<div ng-controller="ControllerB">
<h2>ControllerB</h2>
<pre><code>result = {{ result | json }}</code></pre>
</div>
You can see it in action in this plunker.

Angular radio validation in ng-repeat

I'm trying to create a form that is valid if a radio button is selected. The radio button is part of a group from which the user can choose one. I'm assigning the required attribute to the radio buttons using a function in my controller, and this seems to be causing issues with the validation. I think it's some sort of scope problem but I can't figure it out.
Here's a jsfiddle showing the problem: http://jsfiddle.net/flyingL123/x27nv8fq/5/
You can see that the radio inputs correctly have the required attribute assigned to them, but even if the user doesn't select an option, the form still validates and submits.
Here's the HTML:
<div ng-app="test" ng-controller="TestController">
<form name="testForm" ng-submit="testForm.$valid && submitForm()" novalidate>
<div ng-repeat="option in options">
<input type="radio" name="testInput"
ng-value="option"
ng-model="$parent.selectedOption"
ng-required="required()" />
{{ option.value }}
</div>
<button type="submit">Submit</button>
<p ng-show="testForm.testInput.$invalid">Form is invalid</p>
{{ selectedOption }}
</form>
</div>
And the JS:
var test = angular.module('test', []);
test.controller('TestController', ['$scope', function($scope){
$scope.options = [{id: '0', value: 'blue'}, {id: 1, value: 'green'}]
$scope.selectedOption = {};
$scope.submitForm = function(){
alert('Form valid and submitted');
}
$scope.required = function(){
if(!$scope.selectedOption.id){
return true;
}
return false;
}
}]);
Why is the form considered valid even though a required radio input is not selected?
There were 2 issues that I noticed:
1) The $scope.selectedOption (as you mentioned)
2) The $scope.required function is unnecessary as far as I can tell. You should just set required to true on those inputs - Angular knows via the name attribute that only 1 of the inputs needs to be checked.
You can see it in action here - http://jsfiddle.net/x27nv8fq/6/
HTML
<div ng-app="test" ng-controller="TestController">
<form name="testForm" ng-submit="testForm.$valid && submitForm()" novalidate>
<div ng-repeat="option in options">
<input type="radio" name="testInput"
ng-value="option"
ng-model="selectedOption"
ng-required="true" />
{{ option.value }}
</div>
<button type="submit">Submit</button>
<p ng-show="testForm.testInput.$invalid">Form is invalid</p>
{{ selectedOption }}
</form>
</div>
Javascript
var test = angular.module('test', []);
test.controller('TestController', ['$scope', function($scope){
$scope.options = [{id: '0', value: 'blue'}, {id: 1, value: 'green'}]
$scope.selectedOption;
$scope.submitForm = function(){
alert('Form valid and submitted');
}
}]);
It looks like the issue is that I'm initializing $scope.selectedOption to {} rather than leaving it undefined. I'm guessing that since an empty object is "truthy", Angular considers it valid. Remove this from the code seems to have fixed the problem.

Categories