I have an array of strings like:
questions: [
"Question 1?",
"Question 2?",
"Question 3?",
"Question 4?",
],
Then I have form fields in my data() like:
legitForm: {
name: '', // this will be equal to question string
answer: '',
description: '',
duration: '',
},
Now, the problem I'm facing is when I fill inputs for any of questions
above the same field for other questions gets same value.
Here is my template code:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
<div class="row">
<div class="col-md-12">
<p>
<strong>{{question}}</strong>
</p>
</div>
<div class="col-md-6">
<label for="answer">Answer</label>
<select class="mb-1 field" v-model="legitForm.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="col-md-6">
<label for="duration">Duration</label>
<input class="field" v-model="legitForm.duration" type="text">
</div>
<div class="col-md-12">
<label for="description">Description</label>
<textarea style="height: 190px;" type="text" cols="5" rows="10" id="address" class="mb-1 field" v-model="legitForm.description"></textarea>
</div>
</div>
<button type="submit" class="saveButtonExperience float-right btn btn--custom">
<span class="text">Save</span>
</button>
</form>
</div>
And this is my post method that sends data to backend:
legitStore(question) {
this.legitForm.name = question; // set "name" in `legitForm` to value of `question` string
axios.post('/api/auth/userLegitsStore', this.legitForm, {
headers: {
Authorization: localStorage.getItem('access_token')
}
})
.then(res => {
// reset my data after success
this.legitForm = {
name: '',
answer: '',
description: '',
duration: '',
};
})
.catch(error => {
var errors = error.response.data;
let errorsHtml = '<ol>';
$.each(errors.errors,function (k,v) {
errorsHtml += '<li>'+ v + '</li>';
});
errorsHtml += '</ol>';
console.log(errorsHtml);
})
},
Here is issue screenshot:
Note: I've tried to
change legitForm to array like legitForm: [], and legitForm: [{....}]
add index to my inputs v-model
but I've got errors so i wasn't sure what I'm doing wrong, that's why
I'm asking here.
If you think of your questions as questions and answers, you can do something like this:
questions: [
{
question: 'Question 1',
answer: null,
description: null,
duration: null,
},
{
question: 'Question 2',
answer: null,
description: null,
duration: null,
},
]
Then when looping through your form, it would be more like this:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
...
<select class="mb-1 field" v-model="question.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
...
</form>
</div>
And in the storing function you could send the data in the question instead of this.legitForm
Like you said you tried here:
change legitForm to array like legitForm: [], and legitForm: [{....}]
add index to my inputs v-model
You are supposed to be doing that.
I would change legitForm to:
//create legitForms equal to the length of questions
const legitForms = [];
for (i in questions) legitForms.push(
{
name: '', // this will be equal to question string
answer: '',
description: '',
duration: '',
}
);
and in template:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
<div class="row">
<div class="col-md-12">
<p>
<strong>{{question}}</strong>
</p>
</div>
<div class="col-md-6">
<label for="answer">Answer</label>
<select class="mb-1 field" v-model="legitForms[index].answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="col-md-6">
<label for="duration">Duration</label>
<input class="field" v-model="legitForms[index].duration" type="text">
</div>
<div class="col-md-12">
<label for="description">Description</label>
<textarea style="height: 190px;" type="text" cols="5" rows="10" id="address" class="mb-1 field" v-model="legitForms[index].description"></textarea>
</div>
</div>
<button type="submit" class="saveButtonExperience float-right btn btn--custom">
<span class="text">Save</span>
</button>
</form>
</div>
<div v-for="(question, index) in questions" :key="index">
In your template you iterate through questions and within this tag render object legitForm it all questions will refer to the same 1 object that's why all question have the same data.
You should have had create an array of question contains it own question's content like
<template>
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
...
<div class="col-md-12">
<p>
<strong>{{question.id}}</strong>
</p>
</div>
...
<select class="mb-1 field" v-model="question.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
...
</form>
</div>
</template>
<script>
class QuestionForm {
// pass default value if you want
name = ''
answer = ''
description = ''
duration = ''
id = ''
constructor(form) {
Object.assign(this, form)
}
}
function initQuestions(num) {
// can generate a Set object cause question are unique
return Array.from({ length: num }, (v, i) => i).map(_j => new QuestionForm())
}
export default {
data() {
return {
questions: initQuestions(5), // pass number of question you want to generate
}
}
}
</script>
Related
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: ""
});
},
Im new to laravel and vue.js. I'm developing a simple online examination and Im having a hard time in showing the answer of the user if he/she will click the previous button.
This my template I used v-for to loop the questions:
<div class="myQuestion" v-for="(question, index) in questions" :key="index + uuid">
<div class="row">
<div class="col-md-6">
<blockquote >
Total Questions {{ index+1 }} / {{questions.length}}
</blockquote>
<h2 class="question">Q. {{question.question}}</h2>
<form class="myForm" action="/quiz_start" v-on:submit.prevent="createQuestion(question.question_id, question.answer, auth.id, question.topic_id)" method="post">
<input class="radioBtn" v-bind:id="'radio'+ index" type="radio" v-model="result.user_answer" value="A" aria-checked="false" > <span>{{question.a}}</span><br>
<input class="radioBtn" v-bind:id="'radio'+ index+1" type="radio" v-model="result.user_answer" value="B" aria-checked="false"> <span>{{question.b}}</span><br>
<input class="radioBtn" v-bind:id="'radio'+ index+2" type="radio" v-model="result.user_answer" value="C" aria-checked="false"> <span>{{question.c}}</span><br>
<input class="radioBtn" v-bind:id="'radio'+ index+3" type="radio" v-model="result.user_answer" value="D" aria-checked="false"> <span>{{question.d}}</span><br>
<div class="row">
<div class="col-md-6 col-xs-8">
<button type="submit" class="btn btn-wave btn-block nextbtn">Next</button>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-8">
<button type="submit" class="btn btn-wave btn-block prebtn">Previous</button>
</div>
</div>
</form>
</div>
</div>
</div>
This is my script to fetch the data and insert the data array to questions variable.
<script>
import { v4 as uuidv4 } from 'uuid';
export default {
props: ['topic_id'],
data () {
return {
questions: [],
answers: [],
uuid:0,
result: {
question_id: '',
answer: '',
user_id: '',
user_answer:0,
topic_id: '',
},
auth: [],
}
},
created () {
this.fetchQuestions();
},
methods: {
fetchQuestions() {
this.$http.get(`${this.$props.topic_id}/quiz/${this.$props.topic_id}`).then(response => {
this.questions = response.data.questions;
this.auth = response.data.auth;
this.uuid=uuidv4();
console.log(this.questions);
}).catch((e) => {
console.log(e)
});
},
createQuestion(id, ans, user_id, topic_id) {
this.result.question_id = id;
this.result.answer = ans;
this.result.user_id = user_id;
this.result.topic_id = this.$props.topic_id;
this.$http.post(`${this.$props.topic_id}/quiz`, this.result).then((response) => {
console.log(response.data.message);
let newdata=response.data.newdata;
this.questions.splice(newdata[0]["index"],1,newdata[0]);
}).catch((e) => {
console.log(e);
});
this.result.topic_id = '';
this.result.user_answer =0;
}
}
}
</script>
I used jQuery next() and prev() for the next and previous buttons. In questions variable, I store my array of objects from database which contains the questions and choices so after the user click next it will update the element of questions to insert the answer chosen by the user. My problem is how can I checked the answer by default chosen by the user if the question showed was answered already by the user. This is the time when the user wants to review his/her answers before finishing the exam.
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>
I cannot push to an array.
i have a segment(id, time) that can have one or several people (role, infos). the field are generated dynamically. On load the page shows the fields (see image below).
when try to add a person I get error : ERROR TypeError: Cannot read property 'push' of null
Here is the .ts code:
addPerson(index: number) {
//let personRows3 = <FormArray>this.mySummaryForm.get('personRows3');
let personRows3 = <FormArray>this.mySummaryForm.get(`segmentRows3.${index}.personRows3`)
personRows3.push(this.fb.group({
personR3: '',
personI3: ''
}));
}
segmentRows3: this.fb.array([
this.fb.group({
segmentId3: '',
segmentTime3: '',
personRows3: this.fb.array([
this.fb.group({
personR3: '',
personI3: ''
})
])
})
]),
The .html code
<div formArrayName="segmentRows3">
<div *ngFor=" let segmentRow of mySummaryForm.controls.segmentRows3.controls; let i=index " >
<div class="form-group" [formGroupName]="i" > {{i+1}}
<label for="segmentId3">Segment ID
<select formControlName="segmentId3" formControlName="segmentId3" placeholder="pick" type="text" id="segmentId3" class="form-control" [(ngModel)]="levelNumSegment3" (ngModelChange)="toNumberSegment3()">
<option *ngFor="let level of segmentId" [value]="level.num">{{level.name}}</option>
</select>
</label>
<label for="segmentTime3">Segment time
<input formControlName="segmentTime3" type="text" id="segmentTime3" class="form-control" placeholder="select a time" (ngModelChange)="onChange($event)">
</label>
<div formArrayName="personRows3">
<div *ngFor=" let personRow of segmentRow.controls.personRows3.controls; let j=index " >
<div class="form-group" [formGroupName]="j" > {{j+1}}
<label for="personR3">person Role
<input formControlName="personR3" [typeahead]="personRole" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personR3" class="form-control" placeholder="select a role" (ngModelChange)="onChange($event)" >
</label>
<label for="personI">Person infos
<input formControlName="personI3" [typeahead]="states" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personI3" class="form-control" placeholder="select infos" (ngModelChange)="onChange($event)" >
</label>
<label><span (click)="deletePerson(j)" class="btn btn-danger">Remove</span></label>
</div>
</div>
</div>
<br><button type="button" (click)="addPerson(j)" class="btn btn-info">Add a person</button><br><br><br>
</div>
</div>
</div>
The above error will occur when your personRows3 is null or don't have elements.
Add a check before pushing the elements,
if(personRows3){
personRows3.push(this.fb.group({
personR3: '',
personI3: ''
}));
}
http://plnkr.co/edit/9Yq6aZHtKCuZMtPbjBIN?p=preview
I've tried and tried to get this to work but I've had no luck. I'm trying to disable the submit button using angularJS and the built in validation function. What I find is that when you first load the form, the submit button is active--not disabled!
I've tested and tried and I've found that my validation code accepts an empty string / null string in the Team Name, despite me requiring the input.
Does anyone know how to format this correctly? The ONLY way I've gotten it to work is to fudge the data with replacing an empty string with a single space...in production this is unacceptable...
Here is the index.html:
<body ng-controller="EnterController as enter">
<div class="panel panel-primary">
<div class="panel-body">
<form name="enterFormNew" ng-submit="enter.TeamNameNext()" autocomplete="off" novalidate>
<div class="row">
<div class="col-xs-8 col-md-6">
<div class="form-group">
<label for="teamname">Team Name</label>
<input name="TeamName" ng-required ng-minlength="2" ng-maxlength="40" ng-model="enter.Team.Name" type="text" id="teamname" class="form-control" />
<p ng-show="enterFormNew.TeamName.$touched && enterFormNew.TeamName.$invalid">This is not a valid team name.</p>
</div>
<div class="form-group">
<label for="division">Division</label>
<select name="selectDivision" ng-required ng-model="enter.Team.Division" id="division" class="form-control" ng-options="division.Name for division in enter.Divisions track by division.Id ">
<option value="">Select...</option>
</select>
<p ng-show="enterFormNew.selectDivision.$touched && enterFormNew.selectDivision.$invalid">A valid Division needs to be selected.</p>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<button type="submit" class="btn btn-primary" ng-disabled="enterFormNew.$invalid">Next</button>
</div>
</div>
</form>
</div>
</div>
</body>
And here is the app.js:
angular.module('Enter', [])
.controller("EnterController", [
function() {
this.RegistrationPhase = 0;
this.Divisions = [{ Id: 1,Name: "Normal"}, {Id: 2,Name: "Not Normal"}];
this.Team = { Name: "", ResumeKey: null, Division: { Id: -1 }, Players: []};
this.TeamNameNext = function() {
//Code removed
alert("Made it to the submit function!")
};
}
]);
the attribute ng-required requires a value. Don't get confused with HTML5 attribute required that doesn't require a value.
ng-required="true"
Because "Team.Division" is not undefined in your controller code.
If you could use the code below, you will get what you extected.
this.Team = { Name: "", ResumeKey: null, Division: undefined, Players: []};
You can use null or "" instead of undefined.