Vue-js removed selected date from textbox when add new element - javascript

Vue-js remove selected date from textbox when add new element. if i entered any text instead of date and add new element text is display as is it. but date is removed.
below is my HTML code
<div class="dateAvailabilityContainer">
<div class="dateAvailability" v-for="(date, index) in dates">
<div class="form-group date">
<input type="text" v-model='date.date' class="form-control date" v-bind:class="'datepicker_'+index" placeholder="Date">
</div>
<div class="form-group">
<input type="text" v-model='date.from' class="form-control from" placeholder="From">
</div>
<div class="form-group">
<input type="text" v-model='date.to' class="form-control to" placeholder="To">
</div>
<a href="#" v-if="index == 0" class="btn btn-success" v-on:click="addNewDate">
<i class="fa fa-plus"></i>
</a>
<a href="#" v-if="index > 0" class="btn btn-danger" v-on:click="removeThisDate(index)">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
and below is my vue-js code
var addAvailability = new Vue({
el: '#addAvailability',
data: {
dates : [{
date : '',
from : '',
to : '',
}],
},
mounted: function () {
this.addDatePicker( this.dates.length - 1 );
},
methods: {
addNewDate: function () {
this.dates.push({
date: '',
from: '',
to: '',
});
this.addDatePicker( this.dates.length - 1 );
},
removeThisDate : function(index){
this.dates.splice(index, 1);
},
addDatePicker : function( id ){
setTimeout(function(){
console.log('.datepicker_'+id);
$('.datepicker_'+id).datepicker({
autoclose: true,
});
},500);
}
}
});
please help where i create a mistake.
please check in fiddle : https://jsfiddle.net/renishkhunt/bod4ob5y/19/
Thanks

Bootstrap (js) and jquery aren't friendly working with vue.
I think that it is because they modify DOM directly while vue also has a virtual DOM and works in a more data driven way.
Make them work together requires extra logic, I could only fix datetimepicker, I never haven't work with clockpicker before
First I change addNewDate function
//Save new date in a variable
var dateModel = {
date: '',
from: '',
to: '',
};
this.dates.push(dateModel);
var elementId = "datepicker_"+(this.dates.length - 1);
//pass new date to initDate function
this.initDate( elementId, dateModel );
In initDate we need to listen for date changes and update model
$('#'+id).datepicker({
...
}).on('changeDate', function(e){
dateModel.date = e.format();
});
Please see this partially working fiddle
As alternative you could use vue-flatpickr, at this moment is the best "vue's way" that I have found to handle date time inputs

Related

Clear input fields on remove jQuery

I'm using form, where i have remove function. It is working fine but i want the fields value to be clear when remove function triggered. Because i'm also sending input values to my php script.
This is html
<div class="form-group">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Child name</label>
<input class="thevoornaam character" name="voorname[]" type="text" placeholder="Voornaam"/>
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<!-- <input type="text" size="50" id="URL" onchange="getDoB(this.value)"/> -->
</div>
</div>
</div>
<a class="delete removeButton" href="#" onmouseup="showHint('close','stepname');"><i class="fa fa-times"></i></a>
Here is my js code
(document).ready(function() {
$('#taskForm')
.bootstrapValidator({
framework: 'bootstrap',
fields: {
'task[]': {
// The task is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
notEmpty: {
message: 'The task is required'
}
}
},
'date[]': {
// The due date is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
date: {
format: 'DD/MM/YYYY'
// message: 'Fill valid date of birth'
}
}
}
}
})
.on('added.field.fv', function(e, data) {
if (data.field === 'date[]') {
// The new due date field is just added
// Create a new date picker
data.element
.parent()
// .datepicker({
// format: 'dd/mm/yyyy'
// })
.on('changeDate', function(evt) {
// Revalidate the date field
$('#taskForm').bootstrapValidator('revalidateField', data.element);
});
}
})
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#taskTemplate'),
$clone = $template
.clone(true,true)
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
$("#stepname").addClass("disabled")
// Add new fields
// Note that we DO NOT need to pass the set of validators
// because the new field has the same name with the original one
// which its validators are already set
$('#taskForm')
.bootstrapValidator('addField', $clone.find('[name="task[]"]'))
.bootstrapValidator('addField', $clone.find('[name="date[]"]'))
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).closest('.form-group');
// Remove fields
$('#taskForm')
.bootstrapValidator('removeField', $row.find('[name="task[]"]').val(''))
.bootstrapValidator('removeField', $row.find('[name="date[]"]').val(''));
// Remove element containing the fields
$row.remove();
});
});
Here i'm trying to clear the values but it is not working. Can anyone help here what i'm doing miskate?
Thanks is advance
If all you needed to do is a field clear...
I'm iterating around each one with .each and setting its value to an empty string😊
ES6
$('.delete.removeButton').click(() => {
$('.form-group').find('input').each((i, el) => {
$(el).val('')
})
})
ES5
$('.delete.removeButton').click(function () {
$('.form-group').find('input').each(function (i, el) {
$(el).val('')
})
})
use button instead of anchor tag and add onclick= "clearInput()" into it:
<input type="text" id = "clId" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<button onclick= "clearInput()" >clear value</button>
then in js try like this:
function clearInput(){
$('#clId').val('');
}
follow this given way. hope your problem will be sorted out.

Vue.js - can not add date/timepicker to the html element rendered by vue.js

I have a Vue.js component where there are groups of text fields ( group of a text field labelled "Start" and another text field labelled "To") bound to a Vue array ( s.timespans) .
What I want is, when I add another group of text field by adding element to the ( s.timespans ) array, all the textfields get date/timepicker. But unfortunately, now only the first group of field gets the date/timepicker and the other groups don't. What is the right way of doing this?
Thanks in advance.
<template id="settings">
<div v-for="(k,slot) in s.timespans" class="row mb5">
<div class="col-sm-5">
<label><?php _e( 'From', 'smps' ); ?></label>
<input type="text" class="datepicker form-control" v-model="slot.from">
</div>
<div class="col-sm-5">
<label><?php _e( 'To', 'smps' ); ?></label>
<input type="text" class="datepicker form-control" v-model="slot.to">
</div>
<div class="col-sm-2">
<i class="fa fa-remove"></i>
</div>
</div>
<template>
The Vue js code
Vue.component( 'settings', {
template : '#settings',
data : function () {
return {
s : {
timespans : [
{from : '', to : ''}
]
}
}
},
methods : {
add_timeslot : function () {
Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
$('.datepicker').datetimepicker();
},
remove_timeslot : function (k) {
this.s.timespans.splice(k,1);
},
},
});
Try this then the DOM will be finished rendering, not before nextTick:
add_timeslot : function () {
Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
this.$nextTick(function () {
$('.datepicker').datetimepicker();
});
},
when the function in nextTick is executed, the DOM Element will be rendered.

Bind TextBox, date and dropdownlist value to parameter angularJS wcfRest

I have an angularJS using WCFrest Project
I create dropdownlist and datepicker for parameter to filter showed data.
Search Form can be seen on picture below
This is the html code
<!--Date From-->
<div class="col-md-4">
<input id="txtOldDate" type="date" value="2000-01-01" class="datepicker" />
</div>
<!--Date To-->
<div class="col-md-1">
<label for="labelTo" class="control-label">To</label>
</div>
<div class="col-md-4">
<input id="txtNewDate" type="date" class="datepicker" />
<!-- Set default date value to now-->
<script>
document.getElementById('txtNewDate').value = new Date().toISOString().substring(0, 10);
</script>
</div>
<!--Departement-->
<div class="col-sm-4">
<div class="dropdown">
<select class="form-control" ng-model="DdlDeptManager" ng-change="DdlManager(DdlDeptManager)">
<option ng-repeat="d in GetDeptManager" value="{{d.Department}}">{{d.Department}}</option>
</select>
</div>
</div>
<!--Employee-->
<div class="dropdown">
<!-- #departemen parameter from DdlDeptManager -->
<select id="ddlManagerApproval" ng-model="DdlManager" class="form-control">
<option ng-repeat="m in GetManager" value="{{m.UserName}}">{{m.FullName}}</option>
</select>
</div>
<!--Button Show-->
<div class="col-md-2">
<input id="btnSubmit" type="button" class="btn btn-primary" ng-click="SearchApproval()" value="Show" />
</div>
This is my control approvalCtrl.js
//Control for search purposes
$scope.SearchApproval = function() {
var search = {
//employeeID: $scope.employeeID,
oldDate: $scope.oldDate,
newDate: $scope.newDate,
departemen: $scope.departemen,
approver: $scope.approver
}
var promiseGet = GetApproval.GetApprovalData(search);
//GetApprovalData();
promiseGet.then(function(pl) {
$scope.GetApprovalData = pl.data
},
function(errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
This is the service.js, for employeeID because the session is not created, i forced add value to it on the uri
this.GetApprovalData = function(employeeID, oldDate, newDate, departemen, approver) {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetApproval?employeeID=" + "11321" + "&oldDate=" + oldDate + "&newDate=" + newDate + "&departemen=" + departemen + "&approver=" + approver);
};
My Question is, how to make the value on datepicker id = txtOldDate to give a paramater value to oldDate, txtNewDate to newDate, and other dropdownlist to departemen and approver parameter?
Thanks in Advance.
Hi Randy I have reproduced your code without service sorry for that. Used hardcode array to populate dropdown. Kindly check this url
https://plnkr.co/edit/eSriV68HkhQhzt1yE6DE?p=preview
$scope.GetDeptManager = [{
Department : 'department1'
}, {
Department: 'department2'
}];
$scope.GetManager = [{
FullName : 'manager1'
}, {
FullName: 'manager2'
}]
And you have to assign ng-model values for your input elements so that you will get those values in controller.

Changing from String to Array in AngularJS

I'm building an app to store records in LocalStorage.
Each record is an object in an array, and each record contains multiple objects. The object looks like this:
$scope.recordlist.push(
{
date: $scope.dateJson,
time: $scope.time,
car: $scope.carList.code,
driver: $scope.driverList.name,
from: $scope.locationList.place,
destination: $scope.locationList2.place,
pax: $scope.paxList,
comment: '',
commenttime: '',
arrival: '',
inserted: '',
cancelled:'',
duration:''
}
);
Right now, comment and commenttime are strings.
I create and edit them like this from the front-end:
<div class="col-md-1 msf-button">
<button class="btn-primary"
ng-init="inserted = true"
ng-click="editItem = !editItem"
ng-show="!record.arrival && !record.cancelled && !editItem">
<i class="fa fa-pencil"></i>
</button>
<button class="btn-success"
ng-click="commentTime(record); editItem = !editItem"
ng-show="!record.arrival && editItem && !record.cancelled">
<i class="fa fa-check"></i>
</button>
</div>
<div class="row msf-comment"
ng-show="editItem == true && !record.arrival"
ng-hide="!editItem">
<div class="col-md-12">
<input placeholder="Add a comment"
class="form-control"
ng-model="record.comment">
</div>
</div>
<div class="row msf-comment-row"
ng-show="!editItem && record.comment">
<div class="col-md-12">
<span class="caret"></span>
<span class="comment">
{{record.comment}} - {{record.commenttime}}
</span>
</div>
</div>
The first button will show the first row with the input (comment is added manually)
The second button will hide the input and display the comment, as well as adding commenttime (commentTime(record)):
$scope.commentTime = function (record){
record.commenttime = moment().format("HH.mm");
jsonToRecordLocalStorage($scope.recordlist);
};
The first button will allow to edit this comment, opening the input again and so on.
My problem is as follows: As of now, there's only one comment and one commenttime per record.
How could I manage to turn comment and commenttime into arrays?
I would like to add different comments and different commenttime, more like a checkpoint thing.
EDIT
Following the answer from Spasho I've gotten here:
$scope.recordlist = extractRecordJSONFromLocalStorage();
$scope.addRecord = function () {
$scope.recordlist.push(
{
date: $scope.dateJson,
time: $scope.time,
car: $scope.carList.code,
driver: $scope.driverList.name,
from: $scope.locationList.place,
destination: $scope.locationList2.place,
pax: $scope.paxList,
comment: [{
message: '',
commenttime: ''
}],
commenttime: '',
arrival: '',
inserted: '',
cancelled:'',
duration:''
}
);
$scope.custom = $scope.custom === false ? true: false;
$scope.carList = 0;
$scope.driverList = 0;
$scope.locationList = 0;
$scope.locationList2 = 0;
jsonToRecordLocalStorage($scope.recordlist);
$scope.editItem = false;
};
$scope.commentTime = function (record){
$scope.record.comment.push(
{
commenttime : moment().format("HH.mm")
}
);
jsonToRecordLocalStorage($scope.recordlist);
};
function jsonToRecordLocalStorage(recordlist) {
var jsonRecordlist = angular.toJson(recordlist);
if (jsonRecordlist != 'null') {
localStorage.setItem("recordspax", jsonRecordlist);
} else {
alert("Invalid JSON!");
}
}
But I run into trouble when I try to record data into comment.message and comment.commenttime.
This is the relevant Front end part:
<button class="btn-success"
ng-click="commentTime(record);">
<i class="fa fa-check"></i>
</button>
<div class="col-md-12">
<input placeholder="Add a comment"
class="form-control"
ng-model="record.comment.message">
</div>
<div class="col-md-12"
ng-repeat="comment in record.comment">
<span class="comment">
{{comment.message}} - {{comment.commenttime}}
</span>
</div>
The input with ng-model="record.comment.message" is supposed to store/display the comment, and the commentTime(record) function to store the time.
TypeError: Cannot read property 'comment' of undefined
This is what happens when I trigger commentTime(record) with some text (test) in the input model:
What am I missing?
change the model to make comment an array of objects, e.g.
$scope.recordlist.push(
{
date: $scope.dateJson,
time: $scope.time,
car: $scope.carList.code,
driver: $scope.driverList.name,
from: $scope.locationList.place,
destination: $scope.locationList2.place,
pax: $scope.paxList,
comments: [{
message: 'one comment',
date: new Date()
}],
arrival: '',
inserted: '',
cancelled:'',
duration:''
});
display the comments in an ng-repeat and change input bind
<div class="col-md-12">
<input placeholder="Add a comment"
class="form-control"
ng-model="commentMessage">
</div>
<div class="row msf-comment-row"
ng-show="!editItem && record.comment">
<div class="col-md-12" ng-repeat="comment in record.comments">
<span class="caret"></span>
<span class="comment">
{{comment.message}} - {{comment.date| date: 'yyyy-MM-dd'}}
</span>
</div>
</div>
change commentTime() accordingly
$scope.commentTime = function (record){
record.comment.push(
{
message: $scope.commentMessage,
commenttime : moment().format("HH.mm")
}
);
jsonToRecordLocalStorage($scope.recordlist);
};

Getting data from the server and using ng-options in select control is failing to show options

this my HTML
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button class="btn btn-primary" ng-click="addNewCourse()">Add New Course</button><br/><br/>
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select class="form-control" ng-model="choice.type" ng-options="s for s in coursetoAdd">
<option value="{{s.shortCut}}">{{s.name}}</option>
</select>
</div>
<div class="col-md-6">
<input type="text" placeholder="Enter Course Name" name="" class="form-control" ng-model="choice.course"/>
</div>
</div>
<br/>
</fieldset>
<button class="btn btn-primary" ng-click="convertAndSend()">Submit</button>
</div>
this the js
var timeTable = angular.module("timeTable",[]);
timeTable.controller("addCoursesCtrl", function ($scope,$http) {
$scope.choices = [{ course: '', type: '' }];
$scope.coursetoAdd ;
$http.get("/Semster/getSuggtedCourses").then(function (response) {
$scope.coursetoAdd = response.data;
});
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ course: '', type: '' });
};
$scope.convertAndSend = function () {
var asJson = angular.toJson($scope.choices);
console.log(asJson);
$http.post('/Semster/Add', asJson);
};
});
this code bind an object {"course":...,"type":....} every time you click on add course ,and add input field dynamically , my problem is with select control,I'm getting the data from server and use it with ng-optin ,but all it shows it's just [object Object] in select option not the real value.
Assuming that the data returned from getSuggestedCourses is an array of objects, the ng-options selector:
s for s in courseToAdd
will bind s to each object in the array. You need to bind to the fields in the object like this
s.value as s.name for s in courseToAdd

Categories