I'm trying to store data from form created dynamiclly at runtime.
Please take under consideration that I'm hardcore noob at .js
I got the idea to append HTML with class like this:
<div class="formElement"> some code here </div>
... each time user clicks a buton.
It's all great, but I'm stuck on getting values using angular/jquery from each
of those divs and then parsing them into json format that would match viewmodel class. Can you help me with getting all of them?
The types in each div are:
select list
number input
text input
html code
<div ng-app="formExample" ng-controller="ExampleController">
<button class="btn btn-primary" ng-controller="addRow" ng-click="addLine()">Dodaj przycisk</button>
<form novalidate class="simple-form">
<div class="here">
<div class="formElement">
Klasa:<select class="optns" ng-model="user.class">
<option selected value="1"> Rodzaj... </option>
<option value="2">2</option>
#*tutaj beda dodane opcje*#
</select>
Ilość: <input type="number" ng-model="user.number" value=""/><br />
Uwagi: <input type="text" ng-model="user.text" value=""/><br />
</div>
</div>
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-controller="addRow" ng-click="getValues()" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
angular code
var app = angular.module('formExample', []);
app.controller('ExampleController', ['$scope', function ($scope) {
$scope.master = {};
$scope.nrofrows = 0;
$scope.update = function(user) {
$scope.master = angular.copy(user);
$scope.another = angular.copy()
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
app.controller('addRow', function ($scope) {
$scope.getValues = function () {
var allInputs = $(':input');
#* przy selected ewentualnie jeszcze zamiania :select na klase/id*#
var selected = $(".optns option:selected").each(function ($scope) {
$scope.arraySels.push($(this));
});
var quantities = $('.formElement :input').attr['number'].each(function () {
$scope.arrayQuants.push($(this));
});
var texts = $('.formElement :input').attr['text'].each(function () {
$scope.arrayTexts.push($(this));
});
alert("works" + $scope.arrayQuants);
};
<div ng-app="formExample" ng-controller="ExampleController">
<form novalidate class="simple-form">
<div class="here">
<div class="formElement">
Klasa:<select class="optns" ng-model="user.class">
<option selected value="1"> Rodzaj... </option>
<option value="2">2</option>
#*tutaj beda dodane opcje*#
</select>
Ilość: <input type="number" ng-model="user.number" value=""/><br />
Uwagi: <input type="text" ng-model="user.text" value=""/><br />
</div>
</div>
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update()" value="Copy" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
var app = angular.module('formExample', []);
app.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.user = {};
$scope.nrofrows = 0;
$scope.update = function(user) {
$scope.master = {};
angular.copy($scope.user, $scope.master);
};
}]);
Check with this Demo .I think this will help you
I am not familiar with angular, but if you are using jQuery you can simply use the serializeArray() method to get your form data.
.serializeArray()
Description: Encode a set of form elements as an array of names and values.
Just make sure to add name attributes to your input elements.
Since your form elements are dynamically create you could add a submit event handler to them by delegating the event.
$(document).on('submit', '.simple-form', function(e) {...
Whenever the submit event is triggert you can pass the event target to your getValues function to serialize the form data.
Here is a pure jQuery example, hope it helps.
$(document).on('submit', '.simple-form', function(e) {
getValues(this);
e.preventDefault();
})
var getValues = function (currForm) {
var formData = $(currForm).serializeArray();
console.log(formData);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="formExample" ng-controller="ExampleController">
<button class="btn btn-primary" ng-controller="addRow" ng-click="addLine()">Dodaj przycisk</button>
<form novalidate class="simple-form">
<div class="here">
<div class="formElement">
Klasa:<select name="select" class="optns" ng-model="user.class">
<option selected value="1"> Rodzaj... </option>
<option value="2">2</option>
#*tutaj beda dodane opcje*#
</select>
Ilość: <input name="num" type="number" ng-model="user.number" value=""/><br />
Uwagi: <input name="user" type="text" ng-model="user.text" value=""/><br />
</div>
</div>
<input type="button" value="Reset" />
<input type="submit" value="Save" />
</form>
</div>
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>
Here is my angular view,
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="skipColumn[0]" /><br />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn(skipColumn)">Add SkipColumn</button>
<br />
which adds new textfield every time i click addSkipColumn button.
here is my js code:
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function (skipColumn) {
if($scope.config.skipColumns==null){
$scope.config.skipColumns=[];
}
$scope.config.skipColumns.push([]);
}
so the problem is when I display or see the structure of $scope.config.skipColumns, It gives the following output:
{
skipColumns:[["content of textfield1"],["content of textfield1"]..]
}
But what I need is,`
{
skipColumns:["content of textfield1","content of textfield1",..]
}
please help me.("content of textfield" resfers to form data)
What you need here is to change what you are pushing in config.skipColumns array. Like this:
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
And, ng-repeat would be like:
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" ng-model="config.skipColumns[$index]" />
</fieldset>
(why did I not use skipColumn directly in the ng-model?)
Here's working example:
angular.module("myApp", [])
.controller("ctrl", function($scope) {
$scope.config = {};
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="ctrl">
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="config.skipColumns[$index]" />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn()">Add SkipColumn</button>
<br />
<br>
<pre>{{config.skipColumns}}</pre>
</body>
</html>
See this... Just push value instead of array.
var app = angular.module('angularjs', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = ['choice1'];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push('choice'+newItemNo);
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div ng-app="angularjs" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<select>
<option>Mobile</option>
<option>Office</option>
<option>Home</option>
</select>
<input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
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)"
Hi I have a project using bootstrap ui ?(AngularJS). I want to implement a reset function to reset all the input fields and radio buttons. I've tried to add a new controller in my JS file, but failed. The following is my code.
Html part:
<div ng-controller="AlertDemoCtrl">
<table class="table">
{% verbatim %}
<tr>
<td class="input-group" ng-repeat="(k,v) in alerts">
<span class="input-group-addon">Check {{ k }}</span>
<input type="text" class="form-control" placeholder="Add Check here">
<b>functional check</b> <input type="radio" name="a1">
<b>CFM issue</b> <input type="radio" name="a1">
<b>Defect risk</b> <input type="radio" name="a1">
</td></tr>
{% endverbatim %}
<tr><td><button type="button" class='btn btn-info' ng-click="addAlert()">+Add Check</button>
<button type="reset" ng-click="reset()" class="btn btn-danger">Reset</button>
</td></tr></table></div>
and my JS:
{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http){
$scope.alerts = [];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!'});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
Can some one suggest me a way to make it happen.. Thanks in advance.
You could develop your model a bit more to include a list of properties for each alert:
$scope.addAlert = function() {
$scope.alerts.push({
msg: 'Another alert!',
props: 0,
input: ""
});
};
tie the view to those properties:
<input type="text" class="form-control" placeholder="Add Check here" ng-model="v.input">
<br/>
<b>functional check</b>
<input type="radio" value="fc" ng-model="v.props">
<br/>
<b>CFM issue</b>
<input type="radio" value="cfm" ng-model="v.props">
<br/>
<b>Defect risk</b>
<input type="radio" value="dr" ng-model="v.props">
and then iterate over each alert's properties during the reset:
$scope.reset = function() {
angular.forEach($scope.alerts, function(v) {
v.input = "";
v.props = 0;
});
};
please refer to this plunker I created for you:
http://plnkr.co/edit/JINIgCOTfD2c5dklldQc?p=preview
update:
to hide an element use ng-hide attribute. I updated the plunkr
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>