Make calculation from v-for in vue js - javascript

i'm trying to make simple calculation from data given in vuejs. The calculation is just going well. But, when i started to make sum from calculation total from it, it keeps returning NaN value.
Here is the current code of it:
<div class="row" v-for="fields in data" :key="field.id_m_all_ded">
<div class="col-md-5">
<div class="form-group">
<label>{{ field.name }}</label>
<input type="field.type" class="form-control" #change="calculated(field)" v-model="field.value" />
</div>
</div>
<div class="col-md-7">
<label>Total Deductions</label>
<input type="number" class="form-control" v-model="field.total" disabled />
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Total Allowance</label>
<input type="number" class="form-control" v-model="grandTotal" id="total" disabled />
</div>
</div>
I retrieve the data from my API, and it saved in fields[]:
data() {
return {
model: {
nik: "",
name: "",
basic_salary: "",
period: "",
},
modals: {
modal: false,
},
fields: [{
total: ''
}],
totalData: 11,
page: 1,
mode: "",
};
},
And here's the function:
computed: {
grandTotal: function() {
let temp = 0
for (var i = 0; i < this.fields.length; i++) {
temp = temp + Number(this.fields[i].total)
console.log(temp)
}
console.log(temp)
return temp;
}
},
methods: {
calculated(field){
field.total = 4000000 * (field.value / 100)
console.log(field.total)
}
}
For addtional info, i get the data from the api, but it won't calculate automatic. Therefore, i tried it with manual input first to calculate the value.
What code should i fix from it, because i have no clue.
Thanks

Related

Dynamic generated form with checkbox in Vue

I have dynamic generated form in Vue. Every loop have v-model. Everything work fine. But when I use checkboxes v-model work for all loops not on one like in input type text. Can You help me solved this problem? Below Vue code:
<fieldset>
<div class="form-row mb-2" v-for="input, index in journal" :key="index">
<div class="col-auto">
<label for="date">Data</label>
<Datepicker v-model="input.date" input-class="form-control" :input-attr="{id: 'date', name: 'date'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeStart">Od</label>
<Datepicker type="time" v-model="input.timeStart" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeStart', name: 'timeStart'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeEnd">Do</label>
<Datepicker type="time" v-model="input.timeEnd" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeEnd', name: 'timeEnd'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="players">Lista obecności</label>
<div class="form-check" v-for="item in input.players">
<input v-model="item.checked" type="checkbox" class="form-check-input" :id="'id-'+item.id+'set'+index">
<label class="form-check-label" :for="'id-'+item.id+'set'+index">{{ item.fullName }}</label>
</div>
</div>
<div class="col-auto">
<label for="description">Opis</label>
<textarea v-model="input.description" class="form-control" rows="7" id="description" placeholder="Opis"></textarea>
</div>
<div class="col-auto" #click="addInput" v-show="index == journal.length-1 && journal.length < 16">
<ButtonVue style="margin-top: 30px;" title="Dodaj" type="button" cancelWidth="true" color="btn-success"><i class="fas fa-plus"></i></ButtonVue>
</div>
<div class="col-auto align-self-start" #click="removeInput(index)" v-show="index || ( !index && journal.length > 1)">
<ButtonVue style="margin-top: 30px;" title="Usuń" type="button" cancelWidth="true" color="btn-danger"><i class="fas fa-minus"></i></ButtonVue>
</div>
</div>
</fieldset>
 
data() {
return {
contact: [],
journal: [{
date: "",
timeStart: "",
timeEnd: "",
players: "",
description: ""
}],
contacts: [],
}
},
Methods:
Method for creating dynamic form
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact,
description: ""
});
},
And here is the method which gets players from contacts
getContacts() {
this.pageLoader = true;
this.$http.get('/pkpar/get-contacts')
.then(({
data
}) => {
this.contacts = data.contacts;
for(let i=0; i<this.contacts.length; i++)
{
this.contact.push({'id': this.contacts[i]['id'], 'fullName' :
this.contacts[i]['fullName'], 'checked': true});
}
this.journal[0].players = this.contact;
this.pageLoader = false;
})
.catch(error => {
console.log(error);
});
},
Your addInput method creates and pushes new object into journal array, but each object created this way has a players property which references same array (this.contact)
The Difference Between Values and References in JavaScript
Easiest (but not most optimal) way to handle this is to create a copy of the array and objects inside for each new journal:
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact.map((player) => ({ ...player })),
description: ""
});
},

How do i send Post request with some values of array object to my Back-end in Vue.js

I Have a vue.js model inside which I have several input fields where I am dynamic calculating some value.
What I am trying to do:
When I click on submit I want to console the data in key value pair so that I can send it to back-end, The key part is I want to do it for only those fields Having Value greater then 0
new Vue({
el: '#app',
data() {
return {
totalAmt: 500,
paymentMode: [{
"PAYMENTCODE": "SW",
"PAYMENTNAME": "Swiggy"
}, {
"PAYMENTCODE": "BB",
"PAYMENTNAME": "uber Eats"
}, {
"PAYMENTCODE": "WE",
"PAYMENTNAME": "Zomato"
}]
}
},
computed: {
balAmt() {
// sum of inputs of paymentMode
const sum = this.paymentMode.reduce((a, b) => a + (+b.Amount || 0), 0);
return sum - this.totalAmt;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<label>Total Amt</label>
<input type="text" v-model="totalAmt">
</div>
<div v-for="mode in paymentMode" :key="mode.PAYMENTCODE" class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
<label>{{mode.PAYMENTNAME}}</label>
<input type="text" v-model="mode.Amount">
</div>
<div>
<label>Bal Amt</label>
<input type="text" :value="balAmt">
</div>
<button>Submit</button>
</div>
I know how to do post request using axios the only thimg is how to get key value pairs which are grater then 0
On click Of submit I want to do that.
For this you might use axios library. Here,i add axios cdn link to your code snippet and demonstrate an example for hint.However, this will thrown an error,because the given url is not correct.
new Vue({
el: '#app',
data: {
totalAmt: 500,
paymentMode: [{
"PAYMENTCODE": "SW",
"PAYMENTNAME": "Swiggy"
}, {
"PAYMENTCODE": "BB",
"PAYMENTNAME": "uber Eats"
}, {
"PAYMENTCODE": "WE",
"PAYMENTNAME": "Zomato"
}]
},
computed: {
balAmt() {
// sum of inputs of paymentMode
const sum = this.paymentMode.reduce((a, b) => a + (+b.Amount || 0), 0);
return sum - this.totalAmt;
}
},
methods:{
sendInfo(){
console.log(this.paymentMode);
axios.post("/your/post/url/", {
data: JSON.stringify(this.paymentMode)
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log('please enter a correct url');
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<label>Total Amt</label>
<input type="text" v-model="totalAmt">
</div>
<div v-for="mode in paymentMode" :key="mode.PAYMENTCODE" class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
<label>{{mode.PAYMENTNAME}}</label>
<input type="text" v-model="mode.Amount">
</div>
<div>
<label>Bal Amt</label>
<input type="text" :value="balAmt">
</div>
<button #click="sendInfo">Submit</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js" integrity="sha256-XmdRbTre/3RulhYk/cOBUMpYlaAp2Rpo/s556u0OIKk=" crossorigin="anonymous"></script>

Vue.js: A value in a v-for loop is not staying with the correct array items

I am trying to create a simple application to request a car key for a service department. Obviously the code could be written better, but this is my third day with Vue.js. The time function that is called in the first p tag in the code updates every minutes to keep count of an elapsed time. The problem I am having is when I request a new key the time function doesn't follow the array items as intended. For example, if there are no other requests the first request I submit works perfectly. However, when I submit a new request the elapsed time from my first request goes to my second request. I am sure it could have something to do with the glued together code, but I have tried everything I can think of. Any help would be appreciated.
<template>
<div class="row">
<div class="card col-md-6" v-for="(key, index) in keys" :key="index">
<div class="card-body">
<h5 class="card-title">Service Tag: {{ key.service_tag }}</h5>
<p class="card-text"> {{time}} {{key.reqTimestamp}}min</p>
<p class="invisible">{{ start(key.reqTimestamp) }}</p>
<p class="card-text">Associates Name: {{key.requestor_name}}</p>
<p class="card-text">Model: {{key.model}}</p>
<p class="card-text">Color: {{key.color}}</p>
<p class="card-text">Year: {{key.year}}</p>
<p class="card-text">Comments: {{key.comments}}</p>
<p class="card-text">Valet: {{key.valet}}</p>
<input class="form-control" v-model="key.valet" placeholder="Name of the person getting the car...">
<button
#click="claimedKey(key.id, key.valet)"
type="submit"
class="btn btn-primary"
>Claim</button>
<button v-if="key.valet !== 'Unclaimed'"
#click="unclaimedKey(key.id, key.valet)"
type="submit"
class="btn btn-primary"
>Unclaim</button>
<button class="btn btn-success" #click="complete(key.id)">Complete</button>
</div>
</div>
<!-- END OF CARD -->
<!-- START OF FORM -->
<div class="row justify-content-md-center request">
<div class="col-md-auto">
<h1 class="display-4">Operation Tiger Teeth</h1>
<form class="form-inline" #submit="newKey(service_tag, requestor_name, comments, model, year, color, valet, reqTimestamp)">
<div class="form-group col-md-6">
<label for="service_tag">Service Tag: </label>
<input class="form-control form-control-lg" v-model="service_tag" placeholder="ex: TB1234">
</div>
<div class="form-group col-md-6">
<label for="service_tag">Associates Name: </label>
<!-- <input class="form-control form-control-lg" v-model="requestor_name" placeholder="Your name goes here..."> -->
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select v-model="requestor_name" class="form-control" id="requestor_name">
<option>James Shiflett</option>
<option>Austin Hughes</option>
</select>
</div>
</div>
<div class="form-group col-md-6">
<label for="service_tag">Model: </label>
<input class="form-control form-control-lg" v-model="model" placeholder="What is the model of the vehicle?">
</div>
<div class="form-group col-md-6">
<label for="service_tag">Color: </label>
<input class="form-control form-control-lg" v-model="color" placeholder="What is the color of the vehicle?">
</div>
<div class="form-group col-md-6">
<label for="service_tag">Year: </label>
<input class="form-control form-control-lg" v-model="year" placeholder="What year is the car?">
</div>
<div class="form-group col-md-6">
<label for="service_tag">Comments: </label>
<input class="form-control form-control-lg" v-model="comments" placeholder="Place any additional comments here...">
</div>
<div class="form-group col-md-6 invisible">
<label for="service_tag">Valet: </label>
<input v-model="valet">
</div>
<div class="form-group col-md-6 invisible">
<label for="service_tag">Timestamp: </label>
<input v-model="reqTimestamp">
</div>
<div class="col-md-12">
<button class="btn btn-outline-primary" type="submit">Request A Key</button>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
import { db } from "../main";
import { setInterval } from 'timers';
export default {
name: "HelloWorld",
data() {
return {
keys: [],
reqTimestamp: this.newDate(),
service_tag: "",
requestor_name: "",
comments: "",
color: "",
model: "",
year: "",
inputValet: true,
valet: "Unclaimed",
state: "started",
startTime: '',
currentTime: Date.now(),
interval: null,
};
},
firestore() {
return {
keys: db.collection("keyRequests").where("completion", "==", "Incomplete")
};
},
methods: {
newKey(service_tag, requestor_name, comments, model, year, color, valet, reqTimestamp, completion) {
// <-- and here
db.collection("keyRequests").add({
service_tag,
requestor_name,
comments,
color,
model,
year,
valet,
reqTimestamp,
completion: "Incomplete",
});
this.service_tag = "";
this.requestor_name = "";
this.comments = "";
this.color = "";
this.model = "";
this.year = "";
this.reqTimestamp = this.newDate()
},
complete(id) {
db.collection("keyRequests").doc(id).update({
completion: "Complete"
})
},
// deleteKey(id) {
// db.collection("keyRequests")
// .doc(id)
// .delete();
claimedKey(id, valet) {
console.log(id);
this.inputValet = false
db.collection("keyRequests").doc(id).update({
valet: valet,
claimTimestamp: new Date()
})
},
moment: function () {
return moment();
},
newDate () {
var today = new Date()
return today
},
updateCurrentTime: function() {
if (this.$data.state == "started") {
this.currentTime = Date.now();
}
},
start(timestamp) {
return this.startTime = timestamp.seconds * 1000
}
},
mounted: function () {
this.interval = setInterval(this.updateCurrentTime, 1000);
},
destroyed: function() {
clearInterval(this.interval)
},
computed: {
time: function() {
return Math.floor((this.currentTime - this.startTime) /60000);
}
}
}
</script>
Ideally I am looking for the time lapse to follow each request.
So the problem lines in the template are:
<p class="card-text"> {{time}} {{key.reqTimestamp}}min</p>
<p class="invisible">{{ start(key.reqTimestamp) }}</p>
The call to start has side-effects, which is a major no-no for rendering a component. In this case it changes the value of startTime, which in turn causes time to change. I'm a little surprised this isn't triggering the infinite rendering recursion warning...
Instead we should just use the relevant data for the current iteration item, which you've called key. I'd introduce a method that calculates the elapsed time given a key:
methods: {
elapsedTime (key) {
const timestamp = key.reqTimestamp;
const startTime = timestamp.seconds * 1000;
return Math.floor((this.currentTime - startTime) / 60000);
}
}
You'll notice this combines aspects of the functions start and time. Importantly it doesn't modify anything on this.
Then you can call it from within your template:
<p class="card-text"> {{elapsedTime(key)}} {{key.reqTimestamp}}min</p>

Update nested parent classes in Vue.js

I'm trying to add a class to a parent container each time an "advanced" link is clicked.
So with jQuery I would just write something like..
$(this).closest('.row').addClass('overlay');
or
$(this).closest('section').addClass('overlay');
But it seems to be getting a little complex with Vue to just add a class to the parent container of the item that is clicked. I'm sure there is a more simple way to go about it.
Here is an example of my code.
<div id="app">
<section v-bind:class="{ overlay: i == sectionActive && rowActive == null }" v-for="(section, i) in sections">
Advanced
<div class="advanced-fields" v-bind:class="{ overlay: i == sectionActive && rowActive == null }">
<fieldset>
<label>
ID
<input type="text" name="section[id]" v-model="section.id">
</label>
</fieldset>
<fieldset>
<label>
Class
<input type="text" name="section[css_class]" v-model="section.css_class">
</label>
</fieldset>
</div>
<div class="row" v-bind:class="{ overlay: i == sectionActive && row_i == rowActive }" v-for="(row, row_i) in section.rows">
Advanced
<div class="advanced-fields" v-bind:class="{ overlay: i == sectionActive && row_i == rowActive }">
<fieldset>
<label>ID</label>
<input type="text" name="" v-model="row.id">
</fieldset>
<fieldset>
<label>CSS Class</label>
<input type="text" name="" v-model="row.css_class">
</fieldset>
</div>
</div>
</section>
<pre>{{ $data }}</pre>
</div>
<script>
new Vue({
el: "#app",
data: {
"sections": [{
"id": "section-1",
"css_class": "",
"rows": [{
"id": "",
"css_class": ""
}, {
"id": "",
"css_class": ""
}]
}, {
"id": "section-2",
"css_class": '',
"rows": [{
"id": "",
"css_class": ""
}]
}],
sectionActive: null,
rowActive: null,
columnActive: null
},
methods: {
toggleAdvanced: function(index) {
this.sectionActive = this.sectionActive === index ? null : index;
this.rowActive = null;
this.columnActive = null;
},
toggleRowAdvanced: function(section, row) {
var sectionIndex = this.sections.indexOf(section);
var rowIndex = section.rows.indexOf(row);
this.sectionActive = this.sectionActive === sectionIndex ? null : sectionIndex;
this.rowActive = this.rowActive === rowIndex ? null : rowIndex;
}
}
});
</script>
I need to do the same thing for columns but as you can see, it is getting too overly complicated. Any ideas on how to simplify this?
I know it would be easier to add a data attribute to each row, but I am saving the hash to a database and don't want to add in unnecessary data just for a UI toggle.
https://jsfiddle.net/ferne97/4jbutbkz/
I took a different approach and built several re-usable components. This removes all the complicated logic that you are putting into your Vue.
Vue.component("expand-link",{
template:`Advanced`,
data(){
return {
expanded: false
}
},
methods:{
toggle(){
this.expanded = !this.expanded
this.$emit('toggled', this.expanded)
}
}
})
Vue.component("expanded-fields",{
props:["details", "expanded"],
template:`
<div class="advanced-fields" :class="{overlay: expanded}">
<fieldset>
<label>
ID
<input type="text" name="section[id]" v-model="details.id">
</label>
</fieldset>
<fieldset>
<label>
Class
<input type="text" name="section[css_class]" v-model="details.css_class">
</label>
</fieldset>
</div>
`
})
Vue.component("expandable-section", {
props:["section"],
template:`
<section>
<expand-link #toggled="onToggle"></expand-link>
<expanded-fields :details="section" :expanded="expanded"></expanded-fields>
<expandable-row v-for="row in section.rows" :key="row" :row="row"></expandable-row>
</section>
`,
data(){
return {
expanded: false
}
},
methods:{
onToggle(val){
this.expanded = val
}
}
})
Vue.component("expandable-row",{
props:["row"],
template:`
<div class="row">
<h3>Row</h3>
<expand-link #toggled="onToggle"></expand-link>
<expanded-fields :details="row" :expanded="expanded"></expanded-fields>
</div>
`,
data(){
return {
expanded: false
}
},
methods:{
onToggle(val){
this.expanded = val
}
}
})
And the template simply becomes
<div id="app">
<expandable-section v-for="section in sections" :key="section" :section="section"></expandable-section>
<pre>{{ $data }}</pre>
</div>
Here is your fiddle updated.

Javascript Document.getElementById returning null

I'm new to MVC and AJAX so this is probably a simple mistake I am making but using the code below, I am getting the following error trying to getElementById("txtCount").value:
<div class="row">
<div class="col-sm-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h5 style="font-weight:bold;">Parameters</h5>
</div>
<div class="panel-body" id="parameters">
<form class="form-horizontal" id="frmParameters">
<div class="form-group">
<label for="txtCount" class="col-sm-4 col-form-label">Repeat</label>
<input type="number" min="1" max="100" step="1" id="txtCount" value="#Model.Count" class="input-sm col-sm-7" />
</div>
#if (Model.Grammar.SupportsMaxLength)
{
<div class="form-group">
<label for="txtMaxLength" class="col-sm-4 col-form-label">Max Length</label>
<input type="number" min="1" max="100" step="1" id="txtMaxLength" value="#Model.MaxLength" class="input-sm col-sm-7" />
</div>
}
<button name="btnGenerate" class="btn btn-primary pull-right" onclick="Generate();">Generate</button>
</form>
</div>
</div>
</div>
</div>
<script>
function Generate() {
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
}
</script>
If I change:
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
to:
var data = { count: document.getElementById("txtCount").value};
I don't get the error anymore.
Your code looks fine. I think you are getting the error when your code tries to execute this line
document.getElementById("txtMaxLength").value
Because in your view you are rendering this element when some if condition returns true. So it is possible that your view does not have this input element at all and you are trying to read that! (Check the view source of the page and search for input with txtMaxLength id.
The best solution is to check it exists before trying to read the value.
var data = {
id: "#Model.Id",
count: document.getElementById("txtCount").value,
maxLength: null // or whatever default value you want
};
if (document.getElementById("txtMaxLength")) {
data2.maxLength = document.getElementById("txtMaxLength").value;
}
Or if you are using jQuery library, it is easy
var data = {
id: "#Model.Id",
count: $("#txtCount").val(),
maxLength:$("#txtMaxLength").val()
};

Categories