I have a form like this
<form id="myForm">
<input type="text" name="userName" value="test" />
<ul>
<li ng-repeat="item in list">
<input type="checkbox" name="chkList" value="id" />
</li>
</ul>
</form>
I am using jquery to submit form and converting the post data like this
var d = 'name=' + $('#myform input[name=userName]).val();
var valArr = [];
$('#myform input[name=chkList]').each(function() {
valArray.push($(this).val());
});
d = '&listOfIds=' + valArray.join(',');
... then submitting post with data: d
I dont want to use jquery but not sure what the angualr equivalent would be here?
actually it's all in details, it could be so:
<input type="checkbox" name="chkList" ng-model="valArray[$index]" value="id" />
and in the controller:
$scope.valArray = [ 1 , 2 , 3 ];
Here is what your are looking for: JSFiddle
HTML
<div ng-app="myApp" ng-strict-di>
<div ng-controller="Ctrl">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="$parent.values[item.id]"/>{{item.name}}
</div>
<button type="button" ng-click="submit()">Submit</button>
</div>
JS:
angular.module("myApp",[]).controller("Ctrl",function($scope){
angular.extend($scope,{
values:{},
items:[
{id:1,name:'name1'},
{id:2,name:'name2'},
{id:3,name:'name3'},
],
submit: function() {
var d = '&listOfIds=' + Object.keys($scope.values).join(",");
alert(d);
}
});
});
Related
I have a form with dynamic input. Inputs have same name attributes. So I want to make array for each row.
Like this;
[{'company':'Apple'},{'address':'USA'}],
[{'company':'Samsung'},{'address':'Korea'}]
I am using this simple form (it's dynamic);
<form id='companies'>
<input name='company[]'>
<input name='address[]'>
</form>
And this;
$('form').submit(function(event) {
var newFormData = $('#companies').serializeArray();
console.log(newFormData);
event.preventDefault();
});
Console Log; (All inputs in same array)
[{'company':'Apple'},{'address':'USA'},{'company':'Samsung'},{'address':'Korea'}]
This is an example of solution of your problem :)
<form id='companies'>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
... -> Now you have dynamic containers
</form>
You could use this approach to solve the problem with jQuery.
$('#companies').submit(function(event) {
var $data = [];
var $containers = $(".container-input");
$containers.each(function() {
var $contenedor = $(this);
var $inputCompany = $contenedor.find('input[name^="company"]');
var $inputAddress = $contenedor.find('input[name^="address"]');
var $objectInput = [{
'company': $inputCompany.val()
}, {
'address': $inputAddress.val()
}];
$data.push($objectInput);
});
console.log($data);
});
May help :) more dynamically.
$('#companies').submit(function(event) {
var $data = [];
$.each($(this).children("div"),function(){
obj={};
$.each($(this).find(":input"),function(){
obj[$(this).attr("name").replace("[]","")]=$(this).val();
$data.push(obj);
});
})
console.log($data);
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='companies'>
<div class="input">
<input name='company[]'>
<input name='address[]'>
<input name='phone[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<input type="submit"/>
</form>
I'm using AngularJs & Javascript for my very first application. I'm triying to show info from an API as a checkbox. Right now it's working, but, how can i validate if any of the checkbox options are checked with a submit button?
I was searching here in stackoverflow and find a way, but it's working only with the last option. Here's a part of my html:
<form name="imtesting" ng-submit="imtesting.$valid && validate()" ng-show="$ctrl.coupons.length > 0">
<ul>
<li ng-repeat="c in $ctrl.coupons">
<input type="checkbox"
name="couponBox"
ng-checked="c.Select"
ng-click="$ctrl.selectOne(c)"
ng-model="formData.couponBox" required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<span ng-show="submitted == true && imtesting.couponBox.$error.required">Select at least one cupon!</span></form>
And the button:
<button type="submit" ng-click="submitted = true">Save</button>
Hope you can help me. It's a new world for me this job.
Thanx in advance.
Well, why not create a validation function on your Controller.
Loop over all your coupon objects and check if they have a value.
e.g
$scope.requireCoupon = function() {
var nrCouponsChecked = 0;
$ctrl.coupons.forEach(function(coupon) {
if (coupon.Select) {
nrCouponsChecked++;
}
});
}
// and in your template you would use it like
<span ng-show="submitted == true && requireCoupon()">Select at least one cupon!</span>
That is because you are using the same ng-model for all the checkboxes by doing this:
ng-model="formData.couponBox"
The previous code sets an ng-model (formData.couponBox) for all of the checkboxes.
A valid option would be create an object which will contains the ng-model of every checkbox, like this (Demo with some fake data)
angular
.module('app', [])
.controller("myCtrl", function() {
var wizard = this;
wizard.$ctrl = {
//fake data
coupons: [{
Select: false,
CodeCoupon: "1st"
}, {
Select: false,
CodeCoupon: "2nd"
}],
//create an object for storing the checkbox models
checkBoxModels: {},
checkIfAnyChecked: checkIfAnyChecked
}
return wizard.$ctrl;
function checkIfAnyChecked() {
for (var k in wizard.$ctrl.checkBoxModels) {
if (wizard.$ctrl.checkBoxModels.hasOwnProperty(k) && wizard.$ctrl.checkBoxModels[k]) {
//for instance, if 3rd checkbox is checked, wizard.$ctrl.checkBoxModels will be {3: true} and so on...
return true;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="app" ng-controller="myCtrl as ctrl">
<ul>
<li ng-repeat="c in ctrl.coupons">
<input type="checkbox" name="couponBox" ng-checked="c.Select" ng-click="ctrl.selectOne(c)" ng-model="ctrl.checkBoxModels[$index]" required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<span ng-show="submitted == true && !ctrl.checkIfAnyChecked()">Select at least one cupon!</span>
<br />
<button type="submit" ng-click="submitted = true">Save</button>
</div>
You have to create dynamic names for each checkbox input to do validations.
Here is an example since you have not provided the dataset.
var app=angular.module("App",[]);
app.controller("AppCtrl",function($scope){
var selectedFruits = {
Mango: true
};
var calculateSomeSelected = function() {
$scope.someSelected = Object.keys(selectedFruits).some(function (key) {
return selectedFruits[key];
});
};
$scope.formData = {
selectedFruits: selectedFruits
};
$scope.fruits = [{'name':'Apple'}, {'name':'Orange'}, {'name':'Banana'}, {'name':'Mango'}];
$scope.checkboxChanged = calculateSomeSelected;
calculateSomeSelected();
});
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<form class="Scroller-Container" name="multipleCheckbox" novalidate="" ng-submit="submitForm()">
<h3>What would you like?</h3>
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[fruit.name]" ng-change="checkboxChanged()" ng-required="true" name="fruits_{{$index}}" /> {{fruit.name}}
<p style="color: red;" ng-show="multipleCheckbox.$submitted&&multipleCheckbox.fruits_{{$index}}.$error.required">You must choose {{fruits[$index].name}} fruit</p>
</div>
<input type="submit" value="Submit">
</form>
<pre>Fruits model:
{{formData.selectedFruits | json}}</pre>
</div>
</body>
</html>
I took an example from angularjs.org start page and added some features. One can add new items to the list and they can be nested. But there`re now more than one submit-form and they still share the same ng-module. I need a dynamically generated ng-module variable which exactly is not a big problem as far as I understand. But I have one on functional side where I need to use value assigned to ng-module. If I make a dynamically generated ng-module variable how can I use it then inside the function in the code below (I mean the todoList.todoText in todoList.addTodo):
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.todos = [
{text:'learn angular', done:true},
{text:'build an angular app', done:false,
todos:[
{text:'plan', done: false},
{text:'code', done: false}
]
}
];
todoList.addTodo = function(todo) {
if (!todo) {
todoList.todos.push({text:todoList.todoText, done:false});
return;
}
if (!todo.todos) {
todo.todos = [];
}
todo.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
[ archive ]
<script type="text/ng-template" id="categoryTree">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
<form ng-submit="todoList.addTodo(todo)">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<ul ng-if="todo.todos">
<li ng-repeat="todo in todo.todos" ng-include="'categoryTree'">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
<form ng-submit="todoList.addTodo(todo)">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</li>
</ul>
</script>
<ul>
<li ng-repeat="todo in todoList.todos" ng-include="'categoryTree'"></li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
I know how to solve the problem by means of JavaScript/JQuery but I want to understand how that could be done with Angularjs
I'm working on a list app where initially the user is presented with an input and button. In the input the user enters the name of a new list, and after the button is clicked, an empty list appears ready for input of items. Adding a new list works, as does adding/removing list items. But the name of the list doesn't print on the page. Currently without any advanced CSS, it's expected for the lists' names to all appear at the top of the page rather than directly above their respective lists.
https://codepen.io/anon/pen/RVmeLe
HTML:
<div ng-app="notepadApp">
<div ng-controller="notepadController as notepadCtrl">
<header ng-repeat="list in notepadCtrl.lists">
<form name="removeListForm" ng-submit="notepadCtrl.removeList($index)">
<input type="submit" value="Remove list">
</form>
<h1>{{list.name}}</h1>
</header>
<div ng-repeat="list in notepadCtrl.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
<ul>
<li ng-repeat="item in list.items">
<label>
<input type="checkbox" ng-model="item.checked">
<span class="item-name-wrapper">{{item.name}}</span>
</label>
<form name="itemForm" ng-submit="itemCtrl.removeItem(list, $index)">
<input type="submit" value="remove">
</form>
</li>
</ul>
<form name="itemForm" ng-submit="itemCtrl.addItem(list)">
<input type="text" ng-model="itemCtrl.item.name">
<input type="submit" value="Add item">
</form>
</div>
<form name="addListForm" ng-submit="notepadCtrl.addList(newListName)">
<input type="text" ng-model="notepadCtrl.list.name">
<input type="submit" value="Add list">
</form>
</div>
</div>
Javascript:
(function(){
var app = angular.module('notepadApp', []);
var shoppingLists = [
];
app.controller('notepadController', function(){
var notepadCtrl = this;
notepadCtrl.lists = shoppingLists;
notepadCtrl.addList = function(newListName) {
var newList = {
name: newListName,
items:[]
};
shoppingLists.push(newList);
};
notepadCtrl.removeList = function(index) {
shoppingLists.splice(index, 1);
};
});
app.controller('ItemController', function(){
this.item = {};
this.addItem = function(list){
list.items.push(this.item);
this.item = {};
};
this.removeItem = function(list, index) {
list.items.splice(index, 1);
};
});
})();
You just want to replace:
ng-submit="notepadCtrl.addList(newListName)"
with:
ng-submit="notepadCtrl.addList(notepadCtrl.list.name)"
How can we add a textbox element to a form dynamically using AngularJs. For example in this case, I have a text and textbox which I want to add one other of this pair by clicking on a button using AngularJs.
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<div ng-hide="editorEnabled" ng-click="editorEnabled=true">
{{title}}
</div>
<div ng-show="editorEnabled">
<input ng-model="title">
<button href="#" ng-click="editorEnabled=false">Done editing</button>
</div>
</div>
</div>
<div>
<input type="text" placeholder="Enter answer">
</div>
I implemented it myself. You could dynamically add an element by using ng-repeat in a
<li ng-repeat="elemnt in questionelemnt">
Here it is the Demo: fiddle
js file
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}, {id: 'choice3'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice' +newItemNo});
};
$scope.showAddChoice = function(choice) {
return choice.id === $scope.choices[$scope.choices.length-1].id;
};
html
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>
<input type="text" ng-model="choice.name" name="" placeholder="Enter a restaurant name">
</div>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="element in elements">
<input type="text" ng-model="element.value"/>
</li>
</ol>
<br/>
<b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
<br/>
<br/>
<b>Click here to see ng-model value:</b><br/>
<input type="button" value="submit" ng-click="show(elements)">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var counter=0;
$scope.elements = [ {id:counter, value : ''} ];
$scope.newItem = function(){
counter++;
$scope.elements.push( { id:counter,value:''} );
}
$scope.show=function(elements) {
alert(JSON.stringify(elements));
}
});
</script>
</body>
</html>