Javascript Remove a Template Element - javascript

I have a template that I will simplify as follows:
<script type="text/template" id="contactTemplate">
<div id="contactentry" class="row contact-info">
</div>
<div class="form-group">
<label for="name1">First Name</label>
<input type="text" class="form-control" id="FirstName" name="Contacts[{{ID}}].FirstName" required>
</div>
<div class="form-group minus">
<label for="contactMinus{{ID}}"> </label>
<a id="depminus{{ID}}"><i class="fa fa-minus-circle"></i>Remove</a>
</div>
</script>
I allow insertion of the template, multiple times via the following code, this part works:
<script type="text/javascript">
var clone = (function () {
var cloneIndex = -1;
var template = $('#contactTemplate').text();
return function () {
//Replace all instances of {{ID}} in our template with the cloneIndex.
return template.replace(/{{ID}}/g, ++cloneIndex);
}
})();//self executing function.
var contacts = $('#contacts')
$("#contactadd").on("click", function () {
contacts.append(clone());
window.controlManager.FindControls(contacts);
});
</script>
<div id='contacts'>
<div class="col col-lg-1">
<a id="contactadd"><i class="fa fa-plus-circle"></i>Add</a>
</div>
</div>
Now I am trying to figure out how to make javascript code to remove each element when/if the minus button is clicked (in the template).
I'm not sure what kindof code I could then use to delete the contacts, via the depminus{{ID}} control. Any tips to get me started?

Related

Angular js directive not working in for loop

I am using a diective in ng-repeat which when i click i pass date and time to the function showAppointmentForm but here the problem is when I click on first index of loop i get date and time displayed in modal box but when I click on second ,third and so on its values are coming as function parameters but not displayed.Is this something problem with using directives in for loop.Can anyone please suggest help.Thanks.
Using directive in template,
<div data-ng-repeat="doctor in doctors">
<appointment-timings data-ng-if="appointments" appointments="appointments" physician="doctor.npi" width="2"></appointment-timings>
</div>
My appointmnt directive,
$scope.showAppointmentForm = function(date,time) {
$scope.appointmentData = {};
$scope.appointmentData.physician = $scope.physician;
$scope.appointmentData.date = '';
$scope.appointmentData.time = '';
$scope.appointmentData.date = date.toString();
$scope.appointmentData.time = time;
$scope.submitted = false;
$timeout(function () {
$scope.$apply();
$('#appointments').modal('show');
},500);
}
My Directive html,(A modal box)
<div class="date-time">
<div class="col-md-6 col-xs-6">
<div class="input-group">
<span class="input-group-addon"><b>DATE</b></span>
<input type="text" class="form-control" ng-model="appointmentData.date" disabled>
</div><!-- /input-group -->
</div>
<div class="col-md-6 col-xs-6">
<div class="input-group">
<span class="input-group-addon"><b>TIME</b></span>
<input type="text" class="form-control" ng-model="appointmentData.time" disabled>
</div>
</div>
</div>
<div class="scheduled-hours" id="scheduled-scroll">
<ul>
<li data-ng-click="showAppointmentForm(date, time)" data-ng-repeat="time in times">{{time}}</li>
</ul>
</div>

How to get the class property for each HTML component inside a parent div?

Hello to the community.
This is my HTML code, what I want is to get the class property, only those that start with 'col-sm-', and that is inside the parent div, only identifying it by the property 'kyros'
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="col-sm-8 frm_com ui-droppable"></div>
</div>
</div>
JS:
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']').children('div[class^='+col_sm+']').each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
You should get the following result:
col-sm-2 control-label no-padding-right
col-sm-2
col-sm-8 frm_com ui-droppable
Two changes you need to make:
Use find so you search all descendants, not just children. Not sure why I thought one of your targets was nested inside another, but it isn't; so children is fine if you know they'll be children.
Remove the div restriction from your div[class^=...], because one of the elements you want to find is a label, not a div.
Example:
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']')
.children('[class^='+col_sm+']')
.each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="col-sm-8 frm_com ui-droppable"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But, that's fragile; it requires that the col-sm- be at the beginning of the class attribute. If someone adds a class before it later in development, this will break.
Instead, use a "contains" (*=) as a rough filter and then filter to fine-tune it:
$('div[kyros='+div_parent+']')
.children('[class*='+col_sm+']') // or .find to include descendants
.filter(function() {
// Filter out foo-col-sm-, requiring that col-sm- be at the
// beginning of the string or after a space
return this.className.startsWith(col_sm) || this.className.indexOf(" " + col_sm) != -1;
})
. // ...
Example (I've changed the third match so col-sm- isn't at the beginning of class):
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']')
.children('[class*='+col_sm+']')
.filter(function() {
return this.className.startsWith(col_sm) || this.className.indexOf(" " + col_sm) != -1;
})
.each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="ui-droppable col-sm-8 frm_com"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You aren't getting the first result you expect because you are only looking for div.
$('div[kyros='+div_parent+']').children('div[class^='+col_sm+']').each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
If you change your selector, it will work as expected
.children('*[class^='+col_sm+']')
This solution will work :
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
$('div[kyros='+div_parent+']').find('[class^='+col_sm+']').each(function () {
alert($(this).attr('class'));
console.log($(this).attr('class'));
});
Here is solution done : https://jsfiddle.net/txmmboxf/
I've updated it for lebel selection, now it will select any element start with class name.

Need to append html element as user keep clicking a button with jquery

I am trying to append a div multiple times when clicking a button, the problem is that is only appending once. I need to append same div as user keeps clicking.
DIV I need to append multiple times is stored in a variable named $htmlDivForm in the jquery code.
I'm using bootstrap.
HTML code:
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
jquery code:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append($htmlDivForm);
});
I had gone through your question.
I have Updated the example.
Removed the Object and just inserting plain HTML
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
var htmltext = '<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>'
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append(htmltext);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
<div>
You can't append the same div multiple times, you need to instantiate new divs and attach those. You also don't need to re-wrap the jQuery objects to attach the handlers:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
//Add input text field
$moreFieldsBtn.click(function() {
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
$formUser.append($htmlDivForm);
});

Is this possible using only angular-formly?

So, I have this form, made using AngularJS here, which basically lets me create a purchase object to send to a server, i.e, it lets me select a store where I bought some items, set a "date of purchase" (just a text field for now), and add those items to the object I'm gonna send.
After the submit button it is shown how the model I'm going to send will look like, showing the id of the store, the "datetime", and an array of items.
My question is: Is there a way of doing this form using angular-formly only?
The question arises because I've been reading formly's docs and I haven't figured out how to make it create such a dynamic model as this form does, i.e., with a variable-length array of items of the purchase, or if it is at all possible.
Thanks in advance for any clue you can give me to answer this question :)
The code for the form is as follows:
(function(){
var app = angular.module('test', []);
})();
The html page:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script src="inab.js"></script>
<script src="PurchaseCtrl.js"></script>
</head>
<body ng-app="test">
<div ng-controller="PurchaseCtrl" class="col-md-4">
<h2>Purchase</h2>
<div class="panel panel-default">
<div class="panel-heading">Title</div>
<div class="panel-body">
<div class="form-group">
<label>Store</label>
<select class="form-control" ng-model="model.store">
<option ng-repeat="store in stores" value="{{store.id}}">{{store.name}}</option>
</select>
</div>
<div class="form-group">
<label>date-time</label>
<input class="form-control" type="text" ng-model="model.datetime"/>
</div>
<div ng-repeat="item in items">
<div class="form-group">
<div class="col-sm-2">
<label>{{item.label}}</label>
</div>
<div class="col-sm-8">
<input class="form-control" type="text" ng-model="item.nome" />
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-alert submit-button col-md-2" ng-click="removeItem()">remove item</button>
</div>
</div>
</div>
<button ng-click="addItem()">Add item</button>
</div>
</div>
<button type="submit" class="btn btn-primary submit-button" ng-click="onSubmit()">Submit</button>
<pre>{{model | json}}</pre>
</div>
</body>
</html>
The controller:
(function(){
angular.module('test').controller('PurchaseCtrl', ['$scope', function(scope){
scope.stores = [{id: 1, name:'Store 1'}, {id: 2, name: 'Store 2'}];
scope.items = [];
scope.datetime = '';
scope.store = '';
var i = 0;
scope.model = {
store: scope.store,
datetime: scope.datetime,
items: scope.items
};
scope.addItem = function(){
scope.items.push({label: 'algo' + (i++), nome:''});
}
scope.removeItem = function(){
scope.items.splice(scope.items.length - 1);
}
scope.onSubmit = function(){
console.log(scope.model);
}
}]);
})();
As #Satej commented, it was with repeated sections. Thanks :)

scope values are not getting display in the view

I am new to AngularJS. I stored the response data in the scope in my controller . But the values stored in scope not getting displayed in the html page.
guest-controller.js
var guestProfileApp = angular.module('guestProfileApp', ['guestProfileServices' ]);
guestProfileApp.controller( 'guestProfileController', [ '$scope', 'guestProfileService', GuestProfileController ]);
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.profileBizObj = response.data;
console.log($scope.profileBizObj);
window.location = "profile.html";
});
}
}
profile.html
<html lang="en" ng-app="guestProfileApp">
<body ng-controller="guestProfileController">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="profileBizObj.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="profileBizObj.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="date" class="form-control" placeholder="Date of Birth" id="f_dob" ng-model="profileBizObj.profileData.nameInfo.birthDate">
<div class="input-group-addon"><span class="glyphicon glyphicon-gift"></span></div>
</div>
</div>
</body>
</html>
When I displayed the response data using
console.log($scope.profileBizObj);
The data is displaying correctly. But when I am moving to "profile.html" and trying to display the profileBizObj data using ng-model the values are not getting displayed.
Here is the output of console.log($scope.profileBizObj);
{"addressList":[],
"customerID":"MYCUST",
"emailList":[],
"formattedName":"JOHN PAWLIW, #388569330",
"phoneList":[],
"profileData":{"createdOn":"2015-11-24T14:05:58",
"customerID":"MYCUST",
"nameInfo":{"createdOn":"2015-11-24T14:05:58",
"firstName":"JOHN",
"lastName":"JOHN PAWLIW",
"mergedObjectState":2,
"middleName":"",
"nameInfoID":12642,
"nameTitle":"MR",
"profileID":7183,
"selectedLocale":"en_US",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
"selectedLocale":"en_US",
"status":"ACTIVE",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
}
Please help me as how to resolve this issue . Thank You
In order to display the $scope.profileBizObj in view.html. You can use ng-repeatto iterate through object properties.
<div ng-repeat="item in profileBizObj">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="item.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="item.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
</div>
This is the fiddle link: https://jsfiddle.net/rrwfu834/2/
window.location = "profile.html"
loads a new page. The new page shares no information with the previous page. It's like hitting reload or typing a new url into the browser window.
Looking at your code, simply try removing that line to see if resolves your issue.
There are several ways to load a template within the current page - the easiest of which is probably ng-include.
You can also use routes or ui.router.
The issue is resolved by making following changes
profiletest.html
<body>
<div ng-app="guestProfileApp">
<div ng-controller="guestProfileController">
<button ng-click="getProfile(1546)">Show Profile</button>
<ng-include ng-if="showProfile" src="'profile1.html'"></ng-include>
</div>
</div>
</body>
guest-controller.js
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.showProfile = true;
$scope.profileBizObj = response.data;
});
}
}

Categories