Angular 2: Enable button when form is updated - for-loop

I want to enable a button if at least one field in the form is updated, but when I input some changes in my textarea, the button remains disabled.
I have 3 items in my form - Input Field, Multiple Select Dropdown, Textarea
The button enables when there are changes in the input field or multiple select dropdown, but when I change something in the textarea, it won't enable. Maybe there's something wrong with the for loop and the breaks
Here are my codes:
if (this.data.process == "update") {
for(const f in this.categoryForm.value){
console.log(this.categoryForm.value);
if (f == "categorytags"){
let categorytagsArray = [];
let categorytagsFormArray = this.categoryForm.value[f];
for (const x in this.data.category[f]) {
categorytagsArray.push(this.data.category[f][x]._id);
}
if (categorytagsArray.length != categorytagsFormArray.length) {
this.disableButton = false;
break;
} else {
for (const i in categorytagsFormArray) {
if (categorytagsArray.indexOf(categorytagsFormArray[i]) == -1) {
this.disableButton = false;
break;
} else {
this.disableButton = true;
}
}
}
break;
}
else {
if (this.categoryForm.value[f] == this.data.category[f]) {
this.disableButton = true;
} else {
this.disableButton = false;
break;
}
}
}
}
<div class="dialog-form">
<div class="header">{{data.title}}</div>
<div class="content">
<form class="ui form" [formGroup]="categoryForm" *ngIf="categoryForm" novalidate>
<div class="field required" [class.error]="formErrors.name">
<label>Name</label>
<input type="text" formControlName="name" placeholder="Enter Name..." maxlength="100">
<div *ngIf="formErrors.name" class="field-error">
{{ formErrors.name }}
</div>
</div>
<div class="field required" [class.error]="formErrors.categorytags">
<label>Category Tag</label>
<select name="categorytags" id="categorytags" class="ui fluid dropdown" formControlName="categorytags" multiple="">
<option [attr.value]=categoryTag._id *ngFor="let categoryTag of categorytags">{{ categoryTag.name }}</option>
</select>
<div *ngIf="formErrors.categorytags" class="field-error">
{{ formErrors.categorytags }}
</div>
</div>
<div class="field">
<label>Remarks</label>
<textarea rows="6" formControlName="remark" maxlength="1000"></textarea>
</div>
</form>
</div>
<div class="actions">
<button class="ui basic button" (click)="cancel()">Cancel</button>
<button class="ui primary button" [disabled]="disableButton" (click)="save()">{{data.process.charAt(0).toUpperCase() + data.process.slice(1)}}</button>
</div>
</div>

Related

Return specific data from API when ENTER is pressed

I'm trying to return a specific data when Enter key is pressed. It's something like a barcodes scanner. After each scann scanner enter key code(keyCode = 13) and then app should go through each json object and return the whole json object depends on the scanned barcode.
At this momment I can get whole json... So as I don't need whole json I would like at first to get blank form and after I put barcode in the input field and press ENTER it sould return the sepcific object...
Yeah kind of a complicated task.
index.vue:
<template>
<div class="row">
<div class="card mx-auto">
<div>
<div class="row">
<div class="card w-auto mx-auto">
<div class="card-header">
<div class="row">
<div class="col">
<h3>{{ id }}</h3>
</div>
</div>
</div>
<div class="card-body">
<form >
<div class="form-row align-items-center">
<div class="col">
<input
type="number"
v-model="barcodeSearch"
name="barcode"
class="form-control"
id="inlineFormInput"
placeholder="Barkodas..."
/>
placeholder="Barkodas...">
</div>
</div>
</form>
<table class="table">
<tbody v-if="items">
<div v-for="item in items" :key="item.PrekesID" class="tItems">
<tr >{{ item.Prekes_Pavad}}</tr>
<hr>
<tr >{{ item.Prekes_Kodas}}</tr>
<hr>
<tr >{{ item.PrekesID}}</tr>
<hr>
<div class="col">
<input type="number" name="ItemsFound" class="form-control" id="inlineFormInput"
placeholder="Faktinis likutis">
</div>
<hr>
<div class="col">
<button type="submit" class="btn btn-primary mb-1">Patvirtinti</button>
</div>
</div>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['id'],
data() {
return {
items: []
};
},
mounted() {
fetch("https:**internal address which return json. Example below.**)
.then((res) => res.json())
.then((data) => (this.items = data))
.catch((err) => console.log("err.message"));
},
},
computed: {
searchedBarcode() {
const value = this.barcodeSearch;
let reactiveArray = this.items.filter(function (item) {
if (item && item.Barkodas) {
return item.Barkodas.indexOf(value) > -1;
}
return false;
});
if (reactiveArray.length > 0) {
return reactiveArray;
} else {
return this.items;
}
},
},
</script>
Json exmple:
[
{
"EilesNumeris": 1,
"EilutesNumeris": 1,
"PrekesID": 521328,
"Prekes_Kodas": "5METP000000084",
"Barkodas": "000000220136",
"Prekes_Pavad": "M6-Zn POVERŽLĖ DIN9021",
},
{
"EilesNumeris": 1,
"EilutesNumeris": 2,
"PrekesID": 68316,
"Prekes_Kodas": "5MST000057",
"Barkodas": "0000010008812",
"Prekes_Pavad": "MEDSRAIGČIAI BLT 6,0x40 grūd.D 1/200",
},
{
"EilesNumeris": 1,
"EilutesNumeris": 3,
"PrekesID": 314849,
"Prekes_Kodas": "5MSGR00023",
"Barkodas": "000003962",
"Prekes_Pavad": "%-4,2x19 SAVISRIEGIS Į MET. BE GRĄŽTELIO (AKCIJA)",
},
Use a form submit handler
As we discussed in the comments: Yes, you cannot call barcodeSearch as a method, it is a computed value. But why not create a form handler for the component?
Let's add a form submit handler. You only change this.barcodeSearch in that submit method and don't bind it to the input. This way the only time barcodeSearch is updated is when the form is submitted (pressing enter, clicking search button, clicking "OK" on mobile, etc.).
So remove v-bind="barcodeSearch" from your form first.
Add a submit method for the form:
methods: {
submitForm() {
this.barcodeSearch = this.$refs.searchForm.barcode;
}
}
Then add a submit handler to the form:
...
<form #submit.prevent="submitForm" ref="searchForm">
...
Now the computed value will only change when submitting the form.

how to hide and check a radio button if condition is true

Hy developers pls i have a vuejs code that i would love the radio checked if row.callback_phone starts with 05 or hide the div if callback_phone number is empty. pls my code is below.
<div class="row space" >
<div class="col-md-1">
<input type="radio" name="inp" :value="row.calling_no" aria-selected="true" :checked="checkcall" :disabled="checkInputFunction">
</div>
<div class="col-md-11">
<label class="mol">שלח למספר שממנו חייגו ({{ row.calling_no}})</label>
</div>
</div>
<div class="row space" >
<div class="col-md-1">
<input type="radio" name="inp" :value="row.callback_phone" :checked="checkback" :disabled="checkInputFunction2" >
</div>
<div class="col-md-11">
<label class="mol" >שלח למספר שהלקוח השאיר ({{ row.callback_phone}})</label>
</div>
</div>
my script is below
<script>
export default {
name: "MailModalComponent",
props: {
row: {
type: Object,
default: () => ({}),
}
},
data() {
return {
set_token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
pageUrl: window.pageUrl,
}
},
computed:{
checkcall() {
if (this.row.callback_phone.substring(0, 2) == '05') {
return true;
} else {
return false;
}
},
checkback() {
if (this.row.calling_no.substring(0, 2) == '05') {
return true;
} else {
return false;
}
},
checkInputFunction(){
if(Object.keys(this.row).length > 0){
if(this.row.calling_no == '' ||this.row.calling_no == 'Null' ||
this.row.calling_no?
this.row.calling_no.substring(0,2)!='05':true){
return true;
}else{
return false;
}
}
},
checkInputFunction2(){
if(Object.keys(this.row).length > 0){
if(this.row.callback_phone == '' ||this.row.callback_phone == 'Null' ||
this.row.callback_phone?
this.row.callback_phone.substring(0,2)!='05':true){
return true;
}else{
return false;
}
}
}
},
methods: {
submitToWhatsapp(e) {
e.preventDefault();
},
}
}
i just updated this code, i am fetching the data from my database, but i want conditionally render elements as stated above, please i need help.
Your code worked fine for me. I've included a snippet below with a <input type="text /> to let you change row.callback_phone, then when you type a value starting with 05 the radio button becomes checked.
You can use v-if="row.calling_no && row.calling_no.length" or v-if="row.callback_no && row.callback_no.length" on a div to hide it.
Take a look at the documentation for conditional rendering.
I've added another computed for checkAnyButNotBoth.
new Vue({
el: "#app",
data: () => {
return {
row: {
callback_phone: "",
calling_no: ""
}
}
},
computed: {
checkcall() {
return this.row.calling_no.substring(0, 2) == '05';
},
checkback() {
return this.row.callback_phone.substring(0, 2) == '05';
},
checkAnyButNotBoth() {
return this.checkcall ? !this.checkback : this.checkback;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app">
<div class="row space">
<div class="col-md-1">
<input type="radio" :checked="checkcall" v-if="row.calling_no && row.calling_no.length">
</div>
<div class="col-md-11">
<label class="mol">Calling No: ({{ row.calling_no}})</label>
<input type="text" v-model="row.calling_no" />
</div>
</div>
<div class="row space">
<div class="col-md-1">
<input type="radio" :checked="checkback" v-if="row.callback_phone && row.callback_phone.length">
</div>
<div class="col-md-11">
<label class="mol">Callback Phone: ({{ row.callback_phone}})</label>
<input type="text" v-model="row.callback_phone" />
</div>
</div>
<div class="row">
<div class="col-12">
calling_no starts with 05: {{checkcall}}
</div>
<div class="col-12">
callback_phone starts with 05: {{checkback}}
</div>
<div class="col-12">
either but not both start with 05: {{checkAnyButNotBoth}}
</div>
</div>
</div>

Every row is executed twice

I have found a bug - and I haven't found any solution to this.
I have a code in ASP.NET Core (using VSPro 2019 16.5.0):
public IActionResult CreateSubGroup(MyClass model, string returnUrl = null)
{
if (ModelState.CreateMyClassValidation())
{
if (!db.MyClass.Where(x => x.Title == model.Title).Any())
{
ViewData["ReturnUrl"] = returnUrl;
var code = new MyClass { Title = model.Title, IdGroup = model.IdGroup, GroupCode = model.GroupCode};
db.MyClass.Add(code);
var result = db.SaveChanges();
if (result > 0)//if there was no issue (at least one row was changed)
{
this.AddNotification(MessagesHandler.Success, $"Item\"{model.Title}\" was successfully created.");
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" cannot be created.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" already exists.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"ErrorMessage.");
}
return RedirectToLocal(returnUrl);
}
Creating of new Item always crashes with unique code exception from DB - During debuging I have found, that every row is executed twice (and I don't know why??) - so also the row db.SaveChanges() is executed twice and that's why I got this exception.
Second bad thing is, that not even the first attempt to save database is not executed (= new Item is not created in DB).
Have you seen this error?
EDIT:
I have found, that it happens only when data are posted from view with JS/AJAX (from modal window)
Here is the code for sending data:
<div class="modal fade" id="ModalWindow" tabindex="-1" role="dialog" aria-labelledby="ModalForm" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="ModalForm" action="" method="post" class="validator">
<div class="modal-body">
<div class="form-group">
<label asp-for="Id"></label>
<input class="form-control" asp-for="Id" value="" readonly data-val="false">
<div class="form-text text-muted small">ID cannot be changed!</div>
</div>
<div class="form-group">
<label asp-for="Title"></label>
<input class="form-control mlfb-create" asp-for="Title" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="Title"></span>
</div>
<div class="form-group">
<label asp-for="IdGroup"></label>
<select class="selectpicker form-control" asp-for="IdGroup" data-live-search="true" data-style="btn-info" tabindex="#(++tabindex)">
#if (data?.GroupData != null)
{
#foreach (var item in data?.GroupData)
{
<option value="#(item.Id)">#item.Title</option>
}
}
</select>
</div>
<div class="form-group">
<label asp-for="GroupCode"></label>
<input class="form-control mlfb-create" asp-for="GroupCode" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="GroupCode"></span>
</div>
</div>
<div class="text-center modal-footer">
<button type="submit" class="btn btn-success _modal-buttton-save" tabindex="#(++tabindex)"><i class="fas fa-check mr-2"></i><span>Save</span></button>
<button type="reset" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(function () {
"use strict";
$(document).on('click', '._createSubFormButton', function () {
$('#ModalWindow').modal('show');
$('.modal-title').text('Creating of subgroup');
$('.modal-buttton-save span').text('Create');
$('#ModalForm').attr('action', '/MyCode/CreateSubGroup/?returnurl=' + window.location.href);
});
// Edit form
$(document).on('click', 'tr ._editSubFormButton', function () {
$('#ModalWindow').modal('show');
var $tr = $(this).closest('tr');
var Id = $tr.find('._Id').text();
var Title = $tr.find('._Title').text();
var IdGroup = $tr.find('._IdGroup').text();
var GroupCode = $tr.find('._GroupCode').text();
$('.modal-title').text('Editing of subgroup');
$('#ModalForm').attr('action', '/MyCode/EditSubGroup/' + Id + '?returnurl=' + window.location.href);
$('#Id').val(Id);
$('#Title').val(Title);
$('#GroupCode').val(GroupCode);
});
// form validation reset during closing modal form
$('#ModalWindow').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
$('#IdGroup').load();
$('.form-group .is-invalid').each(function () { $(this).removeClass('is-invalid'); });
$('.form-group .is-valid').each(function () { $(this).removeClass('is-valid'); });
$('.form-text.text-danger').each(function () { $(this).removeClass('text-danger'); });
$('.form-text.text-success').each(function () { $(this).removeClass('text-success'); });
$('.invalid-feedback').each(function () { $(this).remove(); });
});
$(document).on('submit', '#ModalForm', function (e) {
var form = $('#ModalForm');
if (form.valid()) {
console.log(form.serializeArray());
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serializeArray()
}).done(function () {
console.log('done');
$tr.find('._Number').text();
var $tr = $(this).closest('tr');
})
.fail(function () {
console.log('fail');
});
$('#ModalWindow').modal('hide');
}
});
error I got:
Have you tried debugging this code? Debugging with setting breakpoints and stepping through the code would help you find what is wrong with this code.

Dynamic select box data binding on vuejs

i have questions about data binding in vuejs and i hope everyone here can help me to solve this problem.
I'm in the stage of learning to use vuejs with laravel. I have problems doing data bindings in the data editing process, I can not display any information in the select box.
Next I include the data response that i want to display and the code.
data response
{
"data":{
"id":101,
"kode":"B100",
"nama":"Bendung Jules Rutherford",
"desa":{
"id":"5103050018",
"district_id":"5103050",
"name":"BONGKASA PERTIWI",
"district":{
"id":"5103050",
"city_id":"5103",
"name":"ABIANSEMAL",
"city":{
"id":"5103",
"province_id":"51",
"name":"KABUPATEN BADUNG",
"province":{
"id":"51",
"name":"BALI",
}
}
}
}
}
}
and this is the code :
<template>
<div>
<div v-if="!loading">
<div class="form-group row">
<label class="col-sm-3">Kode</label>
<div class="col-sm-9">
<input :class="{'is_invalid' : errors.kode}" v-model="bendung.kode" type="text" class="form-control" placeholder="B0001">
<div class="invalid-feedback" v-if="errors.kode">{{ errors.kode[0] }}</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3">Nama</label>
<div class="col-sm-9">
<input :class="{'is-invalid': errors.nama}" v-model="bendung.nama" type="text" class="form-control" placeholder="Bendungan Mengwi">
<div class="invalid-feedback" v-if="errors.nama">{{ errors.nama[0] }}</div>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.provinces }]">
<label class="col-sm-3">Provinsi</label>
<div class="col-sm-9">
<select #change="province" v-model="bendung.desa.district.city.province_id" class="form-control">
<option value="">Pilih Provinsi</option>
<option v-for="province in provinces" :value="province.id">
{{ province.name }}
</option>
</select>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.cities }]">
<label class="col-sm-3">Kota / Kabupaten</label>
<div class="col-sm-9">
<select #change="city" v-model="bendung.desa.district.city_id" class="form-control">
<option value="">Pilih Kota/Kabupaten</option>
<option v-for="city in cities" :value="city.id">
{{ city.name }}
</option>
</select>
</div>
</div>
</div>
<div class="row" v-else>
<div class="col-sm-12">
<content-placeholders>
<content-placeholders-text/>
</content-placeholders>
</div>
</div>
<div class="form-group row">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<a class="btn btn-success" href="#" :disabled="submiting" #click.prevent="update">
<font-awesome-icon :icon="['fas', 'spinner']" v-if="submiting" />
<font-awesome-icon :icon="['fas', 'check']" v-else/>
<span class="ml-1">Perbaharui</span>
</a>
<a href="/sda/bendung" class="btn btn-danger">
<font-awesome-icon :icon="['fas', 'times-circle']" /> Batal</a>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
errors: {},
bendung: {},
provinces: [],
cities:[],
districts: [],
state: {
province: '',
city: '',
district: '',
},
loading: true,
submiting: false
}
},
mounted() {
this.getBendung();
this.getProvinces();
},
methods: {
getBendung() {
this.loading = true;
let str = window.location.pathname;
let res = str.split("/");
axios.get(`${process.env.MIX_WEBSERVICE_URL}/sda/bendung/${res[3]}`)
.then(response => {
this.bendung = response.data.data;
this.state.province = this.bendung.desa.district.city.province_id;
})
.catch(error => {
this.$toasted.global.error('Bendung tidak ditemukan!');
location.href = '/sda/bendung';
})
.then(() => {
this.loading = false;
});
},
getProvinces() {
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/province`).then(response => {
this.provinces = response.data;
}).catch(error => console.error(error));
},
province() {
this.state.city = '';
const params = {
province: this.state.province
}
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/city`, {params}).then(response => {
this.cities = response.data;
}).catch(error => console.error(error));
},
city() {
this.state.district = '';
const params = {
city: this.state.city
};
// /location/district?city=cityId
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/district`, {params}).then(response => {
this.districts = response.data;
}).catch(error => console.error(error));
}
}
}
</script>
<style scoped>
</style>
the result is like this picture.
i want to show city name on select box but i got blank selectbox and when i change the selectbox (e.g provinsi/province), the other selectbox (e.g. kabupaten/kota/city) will change it data.
You could fetch new data when previous data has been changed.
Here is the working example: https://codesandbox.io/embed/vue-template-2zv2o
Have you tried to use the v-bind:key prop within your v-for loop?
v-bind:key="city.id"
or better with an additional index:
v-for="(city, index) in cities"
[...]
v-bind:key="`${index}-${city.id}`"

How to save state of page even after reloading or closing the browser?

I am working on a quiz application using laravel as backend and vuejs to render the questions on the frontend. The thing that is confusing me how to store the state of quiz even after candidate reloads the page or he/she accidentally close the browser. I am thinking about saving the quiz progress in the database. Is there any better approach than this?
<template>
<div>
<div class="container quiz-steps" v-for="(question,index) in questions" v-bind:key="index">
<div v-show="index === currentIndex && timer>0">
<div>
<span class="badge badge-danger">{{ minutes }}</span>
<span class="badge badge-danger">{{ seconds }}</span>
</div>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" :style="{width: returnTimerWidth()}" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<br>
<div class="container-quiz-question-pills">
<ul class="nav nav-pills quiz-question-pills">
<li> {{ wrong }}<i class="icon-remove"></i></li>
<li> {{ right }} <i class="icon-ok"></i></li>
</ul>
</div>
<div class="question-content">
<p>{{ question.question }}</p>
<!-- Material unchecked -->
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="1" id="radio1" name="materialExampleRadios">
<label class="form-check-label" for="radio1">{{ question.option1 }}</label>
</div>
<!-- Material checked -->
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="2" id="radio2" name="materialExampleRadios">
<label class="form-check-label" for="radio2">{{ question.option2 }}</label>
</div>
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="3" id="radio3" name="materialExampleRadios">
<label class="form-check-label" for="radio3">{{ question.option3 }}</label>
</div>
<div class="form-check">
<input type="radio" v-model="picked" class="form-check-input" value="3" id="radio4" name="materialExampleRadios">
<label class="form-check-label" for="radio4">{{ question.option4 }}</label>
</div>
enter code here
</div>
<br><br><br><br>
<div>
<span> {{index+1}} / {{questions.length}} </span>
<button type="button" class="btn btn-outline-danger float-right btn-next" #click="nextQuestion(question.isCorrect)">Next</button>
</div>
<br>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" :style="{width: returnWidth(index)}" aria-valuenow="100" aria-valuemin=0 aria-valuemax="100"></div>
</div>
</div>
</div>
<div v-if="currentIndex === questions.length || timer==0">
<div class="container thankyou-quiz-page">
<div class="text-center">
<p>Thnakyou for taking the Quiz!</p>
<br>
<div class="thankyou-msg">
<p>You have answered <span>{{ right }}</span> correct answers out of <span>{{ questions.length }}</span>. Your total time was <span>{{ minutesTaken }}:{{ secondsTaken }}</span>. The answers were sent to the administrator and he will contact you shortly.</p>
<p>Your total marks are {{ calculateScore() }}</p>
</div>
<br><br>
<div class="text-center quiz-choice">
Retake the Quiz<br>
Next Quiz
</div>
</div>
<br><br>
<div class="thankyou-message-button">
<button type="button" class="btn ">Retake the Quiz</button>
<button type="button" class="btn float-right ">Next Quiz</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name:'TEST',
props:['quizId'],
data(){
return{
currentIndex:0,
picked:'',
right:0,
wrong:0,
questions:[
],
timer:0,
total:0,
minutes:0,
seconds:0,
minutesTaken:0,
secondsTaken:0,
remainingTime:0,
done:false,
interval: '',
negative: 0,
totalMarks: 0,
type: 0
}
},
methods:{
nextQuestion:function(e){
if(this.picked){
if(e==this.picked){
this.right++;
}
else{
this.wrong++;
}
}
this.currentIndex++;
if(this.currentIndex == this.questions.length){
this.timer = 0;
}
this.picked = '';
},
returnWidth(e){
if( e==0 ){
return 0+'%';
}
else {
return e / this.questions.length * 100+'%';
}
},
returnTimerWidth(){
if( this.remainingTime == 0 )
{
return 0+'%';
}
else{
return this.remainingTime / this.total * 100 + '%';
}
},
loadQuestions(){
axios.get("http://192.168.1.3:8000/api/quiz/"+this.quizId).
then( ({ data }) => ( this.questions = data.data.questions,
this.timer = data.data.timeAllowed * 60,
this.total = this.timer,
this.negative = data.data.negativePercentage,
this.getTime(this)
) )
},
getTime(){
let interval = setInterval( () => {
this.minutes = parseInt(this.timer / 60, 10);
this.seconds = parseInt(this.timer % 60, 10);
this.minutes = this.minutes < 10 ? "0" + this.minutes : this.minutes;
this.seconds = this.seconds < 10 ? "0" + this.seconds : this.seconds;
if (--this.timer <0 ) {
// this.timer = 0;
this.totalTime();
clearInterval(interval);
}
else{
this.remainingTime++;
this.returnTimerWidth();
}
}, 1000);
},
totalTime(){
this.minutesTaken = parseInt(this.remainingTime / 60, 10);
this.secondsTaken = parseInt(this.remainingTime % 60, 10);
this.minutesTaken = this.minutesTaken < 10 ? "0" + this.minutesTaken : this.minutesTaken;
this.secondsTaken = this.secondsTaken < 10 ? "0" + this.secondsTaken : this.secondsTaken;
},
calculateScore(){
this.totalMarks = this.right - ( this.wrong * this.negative );
// if(this.type==1){
// axios.post('http://192.168.1.3:8000/api/quizMarks', {
// Marks: this.totalMarks
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function () {
// // console.log(error);
// });
//
// }
// else if(this.type==0){
// axios.post('http://192.168.1.3:8000/api/quizMarks', {
// Marks: this.totalMarks
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function () {
// // console.log(error);
// });
// }
return this.totalMarks;
}
},
created() {
this.loadQuestions();
}
}
</script>
One way is to use local storage and check if the key exists once the page is loaded.
A cleaner way is to use vuex https://vuex.vuejs.org/ and a local storage plugin such as vuex persist.

Resources