creating textbox element dynamically and bind different model - javascript

I am working in angular js application, where i need to create textbox with buttons dynamically that means
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc9">
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}">Delete</span> <span>Cancel </span> <span id="addRow" style="cursor:pointer" ng-click="ndcCheck(0)">Add </span>
</div>
</div>
this will create below one
i will enter some value in above textbox and click add ,it needs to be created in next line with same set of controls that means (textbox with above 3 buttons need to be created again with the entered value).
Entering 123 in first textbox and click add will create new textbox with delete,cancel,add button with entered value.
Again am adding new value 243 then again it needs to create new textbox down to next line with the entered value (and also the same controls).
finally i want to get all the entered values. how can i achieve this in angular js

You could use ng-repeat with an associative array. Add Would basically push the model value to an array and and also an empty object in the array.
<div ng-repeat ="ndc in NDCarray">
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc.val">
</div>
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}" ng-click="NDCdelete($index)">Delete</span>
<span>Cancel </span>
<span id="addRow" style="cursor:pointer" ng-click="NDCadd ()">Add </span>
</div>
</div>
</div>
In the controller:
$scope.NDCarray = [{val: ''}];
$scope.NDCadd = function() {
$scope.NDCarray.unshift(
{val: ''}
);
};
$scope.NDCdelete = function(index) {
$scope.NDCarray.splice(index, 1);
};
Plunker: https://plnkr.co/edit/3lklQ6ADn9gArCDYw2Op?p=preview

Hope this helps!!
<html ng-app="exampleApp">
<head>
<title>Directives</title>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('exampleApp', [])
.controller('defaultCtrl', function () {
vm = this;
vm.numbers = [1, 2, 3];
vm.add = function (number) {
vm.numbers.push(number);
}
vm.remove = function (number) {
var index = vm.numbers.indexOf(number);
if(index>-1){
vm.numbers.splice(index, 1);
}
}
});
</script>
</head>
<body ng-controller="defaultCtrl as vm">
<div ng-repeat="num in vm.numbers">
<span>Number : {{num}}</span>
</div>
<div>
<input type="number" ng-model="vm.newNumber">
<button ng-click="vm.add(vm.newNumber)">Add</button>
<button ng-click="vm.remove(vm.newNumber)">Remove</button>
</div>
</body>
</html>

Related

Adding HTML-code for every click with ng-click

I am struggling to understand how to implement an add-function that adds a bit of HTML-code each time I click on a plus-button. The user should be able to add how many questions he/she wants, which means each time you click the button, the new code should be added underneath the previous one. Also I want the input to be added to an array in vm.createdset.question. This is the code I want to add each time I click on a button:
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga 1</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="vm.createdset.question.text"></textarea>
</div>
</div>
The button-code:
<i class="fa fa-plus-circle fa-3x new" aria-hidden="true"></i>
You can do this using ng-repeat and an array. All HTML within the div containing the ng-repeat will be repeated for every item in your array.
If you want to keep track of the number of the question you could add newQuestion.id = questionList.length to $scope.addQuestion and instead of using {{$index + 1}} you'll use {{question.id}} instead.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.questionList = [];
$scope.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
$scope.questionList.push(newQuestion);
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
</div>
</body>
</html>
According to your comments, this should be what you're looking for in your particular case:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, adminService) {
var vm = this;
vm.questionList = [];
vm.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
vm.questionList.push(newQuestion);
};
vm.save = function() {
adminService.create(vm.questionList);
};
});
app.service('adminService', function() {
var create = function(answers) {
//Handle your answers and send the result to your webserver.
console.log(answers);
}
return {
create: create
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl as controller">
<button ng-click="controller.addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in controller.questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
<div>
<button ng-click="controller.save()">Save</button>
</div>
</div>
</body>
</html>

jQuery incrementing a cloned elements instead of cloned div

I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
And here is the jQuery Script:
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).closest(".rounded").clone()
.insertAfter(".rounded:last")
.attr("id", "rounded" + (cloneIndex+1))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = id.split('-')[0] +'-'+(cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parent().parent(".rounded").remove();
}
The problem is that the whole div is being cloned and just the div id is being changed:
Here is the id of each div is being incremented:
I need to clone the 2 elements only not the whole div and buttons
At the end I need t add them to database using Ajax and PHP
Here you can go with the code.
In this code i made changes in clone()
Here the changes
You first find existing child element.
Than clone that element and append it after last element
var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html
the below code just only make clone of clonedInput not a whole div
Edit
I also edit remove function also.
It will only removes last element which was cloned.
Hope this will helps you. :)
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex+1));
}
function remove() {
$(".rounded").find(".clonedInput:last").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
You can add style to your actions class to prevent it from showing on all cloned elements
css
.actions {
display: none;
}
.clonedInput:first-child .actions {
display: block;
}
Also for the removing function you could use .closest() instead of .parent().parent()
$(this).closest(".rounded").remove();
There are a lot of things that could be optimized and replaced but I've edited your code. I believe that this is the easiest way to learn.
The edits are marked as "STACKOVERFLOW EDIT" in the comments.
$(document).ready(function() {
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
$("button.submit").on("click", submit_form); // STACKOVERFLOW EDIT: execute the submit function
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex + 1));
}
function remove() {
if($(".clonedInput").length > 1) { // STACKOVERFLOW EDIT: Make sure that you will not remove the first div (the one thet you clone)
$(".rounded").find(".clonedInput:last").remove();
} // STACKOVERFLOW EDIT
}
// STACKOVERFLOW EDIT: define the submit function to be able to sent the data
function submit_form() {
var ajax_data = $('#submit_form').serialize(); // The data of your form
$.ajax({
type: "POST",
url: 'path_to_your_script.php', // This URL should be accessable by web browser. It will proccess the form data and save it to the database.
data: ajax_data,
success: function(ajax_result){ // The result of your ajax request
alert(ajax_result); // Process the result the way you whant to
},
});
}
The HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<form action="" method="post" id="submit_form"> <!-- STACKOVERFLOW EDIT: generate a form to allow you to get the data in easy way -->
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data[]" id="diagnosis_data"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity[]" id="medication_quantity"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
</form> <!-- STACKOVERFLOW EDIT -->
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
<button class="btn btn-danger submit">Submit</button>
</div>
<!-- End class="col-sm-4" -->
</div>

can't reset form input using ng-click

I want to reset input value using ng-click to add it's value to a $scope var then reset the input value
here is my html
<form ng-controller="questionsCTRL" class="ui large form" name="questionForm" ng-submit="addSurvey(questionForm)" novalidate>
<div class="ui segment" id="quest-answers">
<div class="two fields">
<div class="field">
<label>Add New Answer</label>
<div class="ui action input">
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
<button type="button"
ng-click="addAnswer(questionForm.answers.$viewValue)"
ng-disabled="questionForm.answers.$invalid"
class="ui teal right labeled icon button">
<i class="add icon"></i>
Add
</button>
</div>
<small ng-show="questionForm.answers.$invalid" class="ui meta teal">Answers is required</small>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="eleven wide column">
<div class="field">
<div class="ui attached segment" ng-repeat="answer in answerGroup">
{{answer.text}}
<a href class="ui right floated link"><i class="circular delete icon"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
and this is controller content
UIASSIGN1.controller('questionsCTRL', function($scope , $rootScope , $state, $stateParams , $http ) {
// #dummy controller
$rootScope.sectorName = 'Questions';
var _SID = $stateParams.id;
$scope.answerGroup = [];
$http.get("api/survey/survey.json")
.then(function(response) {
var surveyArray = response.data;
$scope.surveyArray = [];
for (var i = 0; i < surveyArray.length; i++) {
var thisItem = surveyArray[i];
var thisElm = {name:thisItem.name,value:parseInt(thisItem._id)};
$scope.surveyArray.push(thisElm)
}
});
$scope.addAnswer = function(answer){
var inArray = {
text : answer
};
$scope.answerGroup.push(inArray);
$scope.questionForm.answers = {};
}
});
this ng-click adds value to $scope.userGroups but it doesn't reset the form input value only resets the $scope.questionForm.answers value to {}
As I mentioned in the comments the value of $scope.answer is mapped to this element:
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
The ng-model="answers" means to define a variable called answers in the scope. Then in angular you can access it with $scope.answers, that is why:
$scope.answers = "";
Will reset the input element.
You could do it like this. Define the answer on the scope
$scope.theAnswer = '';
Set this as your ngModel for the input field:
ng-model="theAnswer"
Simplify your ng-click like this and add the answer to the array directly in the controller and then cleanup the answer:
ng-click="addAnswer()"
$scope.addAnswer = function(){
var inArray = {
text : $scope.theAnswer
};
$scope.answerGroup.push(inArray);
$scope.theAnswer = '';
}

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Categories

Resources