clone form include dependent fields by vuejs - javascript

I have a form in which there should be submitting a price for various health care services. Treatments are already categorized. Now, I want to first select a treatment group from a selector and then select the treatment list for that category in the next selector. When I have just one form on the page, I have no problem. But I need to clone this form and the user can simultaneously record the price of some treatments. In this case, all the second selectors are set according to the last selector for the categories. While having to match their category's selector. I searched for the solution very well and did not get it. My code in vuejs is as follows. Please guide me. Thank you in advance.
<template>
<div>
<div id="treatment_information">
<div class="col-md-3">
<select id="category_name" class="form-control show-tick"
v-on:change="getTreatmentList($event)"
name="treatment_rates[]category_id" v-model="treatment_rate.category_id"
>
<option value="0"> -- select category --</option>
<option class="form-control main"
v-for="item in vue_categories" :id="item.id+1000" :value="item.id"
:name="item.name">
{{ item.name }}
</option>
</select>
</div>
<div class="col-md-3">
<select id="treatment_id" class="form-control show-tick"
name="treatment_rates[]treatment_id" v-model="treatment_rate.treatment_id"
>
<option value="0"> -- select treatment --</option>
<option class="form-control main"
v-for="item in vue_treatments" :value="item.id">
{{ item.value }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
vue_temp: [],
vue_categories: [],
vue_treatments: [],
vue_category: '',
//for clone form
treatment_rate: {
category_id: 0,
treatment_id: 0,
hospital_id: 0,
dollar: 'دلار',
rial: 'ریال'
},
treatment_rates: [],
};
},
mounted() {
console.log('Component mounted.');
this.getList();
},
methods: {
getList() {
var self = this;
axios.get('/vueDashboard/get/categories').then(function (response) {
self.vue_temp = response.data;
const len = self.vue_temp.length;
self.vue_temp.forEach(function (item) {
if (self.vue_right.length > 0) {
while (self.vue_right[self.vue_right.length - 1] < item['rgt']) {
self.vue_right.pop();
if (self.vue_right.length == 0)
break;
}
}
self.vue_categories.push({
'id': item['id'],
'name': '---'.repeat(self.vue_right.length) + ' ' + item['name']
});
self.vue_right.push(item['rgt'])
var str = "---";
});
}).catch(function (error) {
console.log(error);
});
axios.get('/vueDashboard/get/treatments?category=' + JSON.stringify(self.treatment_rates)).then(function (response) {
console.log(response.data);
self.vue_treatments = response.data;
}).catch(function (error) {
console.log(error);
});
},
addForm(event) {
var self = this;
self.vue_increment_id[self.vue_counter++]=self.vue_counter;
console.log(self.vue_increment_id);
self.treatment_rates.push(Vue.util.extend({}, self.treatment_rate));
},
}
}
</script>

Related

How to clear input fields after adding a new element?

I have an array with the students.
I have the implementation of the addition of students.
Question: how to clean up after pressing the field? Fields must be cleaned so that when you try to enter new values ​​were not set to the old values.
Tried everything, nothing works. Neither the <form> -> <button type = "reset">, or the selectors ...
What can be done to solve this problem?
index.html
......
<!-- add new student -->
<br>
<input v-model="students.name" placeholder="surname">
<select v-model="students.group">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input v-model="students.year" placeholder="Bitrh year">
<input type="checkbox" v-model="students.done">
<label>done</label>
<input v-model.number="students.mark" type="number" placeholder="mark">
<button type="reset" #click="addStudent()">add to array</button>
</div>
<!-- /add new student -->
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="/index.js"></script>
index.js
let students = [
{
id: '1',
name: "Test",
group: "1",
year: "1985",
done: true,
mark: 4,
},
]
var app = new Vue ({
el: '#app',
data: {
students: [],
search: '',
stud: students.slice(),
},
methods: {
deleteStudent(studId) {
this.stud = this.stud.filter(elem => {
return elem.id != studId;
});
},
addStudent() {
const id = this.stud.length + 1;
this.stud.push({ id, ...this.students });
}
}
})
I don't know vue, but you can always select all inputs and set it's value on '' :
document.querySelectorAll('input').forEach(input => input.value='')
in best case apply it to container so sth like that:
document.querySelector('.formClassName').querySelectorAll('input').forEach(input => input.value='')
Just use following:
deleteStudent(studId) {
this.stud.splice(students.id, 1)
}
You can splice something based on it's id the 1 after the comma is that it deletes 1 stud-data from your id.
When you want to use a v-model on your form and let the user enter some data, you should pass an initial object to your inputs. And when the user submits the form, you'll push that data to your array, following to reset your initial object.
So this implementation will help you:
<!-- add new student -->
<br>
<input v-model="initialState.name" placeholder="surname">
<select v-model="initialState.group">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input v-model="initialState.year" placeholder="Bitrh year">
<input type="checkbox" v-model="initialState.done">
<label>done</label>
<input v-model.number="initialState.mark" type="number" placeholder="mark">
<button type="reset" #click="addStudent()">add to array</button>
</div>
<!-- /add new student -->
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="/index.js"></script>
var app = new Vue ({
el: '#app',
data: {
students: [],
initialState: {
id: '',
name: '',
group: '',
year: '',
done: true,
mark: 0
},
search: '',
},
methods: {
deleteStudent(studId) {
this.students = this.students.filter(elem => {
return elem.id != studId;
});
},
addStudent() {
const id = this.students.length + 1;
this.students.push({ id, this.initialState });
this.initialState = JSON.parse(JSON.stringify({
id: '',
name: '',
group: '',
year: '',
done: true,
mark: 0
}));
}
}
})

How to get Dropdown data using Vue JS?

my dropdown is not getting any value from my database, it keeps return {{item.cmp_Name}}, Is there anything i have missed?
<label for="user_CompID" class="col-form-label">Company Name</label>
<select class="form-control" name="user_CompID">
<option value="">Select Company Name</option>
<option v-for="item in sel_comp" :value="item.cmp_id">{{item.cmp_Name}}</option></select>
Script
var vm = new Vue({
el: '#maint_user_ctrl',
data: {
sel_comp: []
},
created: function () {
this.doLoadParam();
},
mounted: function () {
$(".bt-table").bootstrapTable();
var dropdownMenu;
$('.bt-table').on('show.bs.dropdown', function (e) {
dropdownMenu = $(e.target).find('.dropdown-menu');
$('body').append(dropdownMenu.detach());
var eOffset = $(e.target).offset();
dropdownMenu.css({
'display': 'block',
'top': eOffset.top + $(e.target).outerHeight(),
'left': eOffset.left
});
});
$('.bt-table').on('hide.bs.dropdown', function (e) {
$(e.target).append(dropdownMenu.detach());
dropdownMenu.hide();
});
},
methods: {
doLoadParam: function () {
var self = this;
ajaxJsonProcess("get", myPath + "/company-dropdown", "", function (inDat) {
self.sel_comp = inDat;
}, dftError);
},
i try debug, it getting the dropdown value but not displaying
If you see the string {{item.cmp_Name}} instead of the results so you didnt setup vue well from webpack / cli.
Also you should check if the request to the server is send because you have problem there.
Move your doLoadParams into methods property.
{
created() { ... },
methods: {
doLoadParam() { ... }
}
}
Also if you need this request to run when component is mounted you can load the request itself from the mounted hook.
Make sure you are getting the values from the rest api. Add console.log and confirm you are getting response from Rest api.
doLoadParam: function () {
var self = this;
ajaxJsonProcess("get", myPath + "/company-dropdown", "", function (inDat) {
console.log('inDat', inDat)
self.sel_comp = inDat;
}, dftError);
}
Or else try the below steps
Step 1: HTML template like
<div id="app">
<label for="user_CompID" class="col-form-label">Company Name</label>
<select class="form-control" name="user_CompID" v-model="selectedCompany">
<option value="">Select Company Name</option>
<option
:key="index"
v-for="(item, index) in sel_comp"
:value="item.cmp_id"
>
{{ item.cmp_Name }}
</option>
</select>
{{ selectedCompany }}
</div>
Step 2: data modal will be
data() {
return {
selectedCompany: "",
sel_comp: [],
};
},
Step 3: methods loadFromAPI function for loading data from api. I just added dummy data instead of api call.
methods: {
loadFromAPI() {
// Load from AJAX API
this.sel_comp = [
{
cmp_Name: "Cognizant",
cmp_id: "cts",
},
{
cmp_Name: "Infosys",
cmp_id: "infy",
},
{
cmp_Name: "Accenture",
cmp_id: "acc",
},
];
},
},
Step 4: By default page load get company details from api by created
created() {
this.loadFromAPI();
},
DEMO
Html
<label for="user_CompID" class="col-form-label">Company Name</label>
<select class="form-control" name="user_CompID" v-model="company">
<option value="" selected>Select Company Name</option>
<option v-for="item in sel_comp" :key="item.cmp_id">{{item.cmp_Name}}</option></select>
Script
data: { company:'',
sel_comp: []
},
mounted: function () {
//the function can be called in mounted.
this.doLoadParam();
$(".bt-table").bootstrapTable();
var dropdownMenu;
$('.bt-table').on('show.bs.dropdown', function (e) {
dropdownMenu = $(e.target).find('.dropdown-menu');
$('body').append(dropdownMenu.detach());
var eOffset = $(e.target).offset();
dropdownMenu.css({
'display': 'block',
'top': eOffset.top + $(e.target).outerHeight(),
'left': eOffset.left
});
});
$('.bt-table').on('hide.bs.dropdown', function (e) {
$(e.target).append(dropdownMenu.detach());
dropdownMenu.hide();
});
},

Laravel 7 - Trouble retrieving old value of dynamic select when validation fails

The form has a select for Customer with populates from a variable in the controller. I can easily retrieve the old input value using old('customer_id').
My problem comes from the second select. The second select uses javascript to populate the Customer Contact based on which Customer is chosen. When validation fails, I lose that value.
Here is the controller code for the store method:
$rules = [
'number' => 'required',
'customer_id' => 'required',
'contact_id' => 'required',
'payment_type' => 'nullable',
'department_id' => 'required',
'requested_ship_date' => 'required|after:yesterday',
];
$customMessages = [
'number.required' => 'The Sales Order number is required.',
'customer_id.required' => 'Please choose a customer.',
'contact_id.required' => 'Please choose a contact.',
'requested_ship_date.required' => 'You must enter a ship date.',
'requested_ship_date.yesterday' => 'The requested ship date must be today or after.',
'department_id.required' => 'Please choose a department.'
];
$salesorder = \request()->validate($rules, $customMessages);
SalesOrder::create($salesorder);
return redirect('/salesorders');
Here is Customer Select:
<select
name="customer_id"
class="shadow text-sm">
#if (old('customer_id'))
<option
value>
</option>
#else
<option
selected
value>
</option>
#endif
#foreach($customers as $customer)
#if (old('customer_id'))
<option
value="{{ $customer->id }}" {{ old('customer_id') == $customer->id ? 'selected' : '' }}>
{{ ucfirst($customer->name) }}
</option>
#else
<option
value="{{ $customer->id }}">
{{ ucfirst($customer->name) }}
</option>
#endif
#endforeach
</select>
Here is the select for the Customer Contact:
<select
name="contact_id"
class="shadow text-sm text-center"
>
<option>
</option>
</select>
And here is the javascript:
$('select[name="customer_id"]').on('change', function () {
var customerId = $(this).val();
if (customerId) {
$.ajax({
url: '/customer/contacts/get/' + customerId,
type: "GET",
dataType: "json",
beforeSend: function () {
$('#loader').css("visibility", "visible");
},
success: function (data) {
$('input[name="email"]').val('');
$('select[name="contact_id"]').empty();
$('select[name="contact_id"]').append('<option value="Choose">Choose Contact</option>');
$.each(data, function (key, value) {
$('select[name="contact_id"]').append('<option value="' + key + '">' + value + '</option>');
});
},
complete: function () {
$('#loader').css("visibility", "hidden");
}
});
} else {
$('select[name="customer_id"]').empty();
}
});

How can I do pagination in html vue js?

How can I able to to do pagination in html vue js. When I click on first page I need to set the offset as 0, when I click on 2 page i need to send offset as 100 and so on. How can I able to send offset like that.
My html code for pagination is
<div class="col-md-12">
<div class="pull-right">
<div class="pagination">
<ul>
<li>Prev</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>Next</li>
</ul>
</div>
</div>
</div>
<div class="items-per-page">
<label for="items_per_page"><b>Property per page :</b></label>
<div class="sel">
<select id="items_per_page" name="limit" v-model="limit">
<option value="3">3</option>
<option value="6">6</option>
<option value="9">9</option>
<option selected="selected" value="12">12</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
<option value="60">60</option>
</select>
</div><!--/ .sel-->
</div><!--/ .items-per-page-->
Based on the offset I need to go on adding the pages. How can it be possible.
My views.py is
#csrf_exempt
def search(request):
if request.method == 'POST':
category = request.POST.get('category')
city = request.POST.get('city')
name = request.POST.get('name')
d = {
'category': category,
'city': city,
'name': name,
}
return render(request, "search.html", d);
else:
# do the thing you want to do in GET method
return render(request,"search.html",{});
My urls.py is
url(r'^search',views.search),
My vue js code is
<script>
searchContent = new Vue({
el: "#searchContent",
data: {
vector: {}
}
});
categories = new Vue({
el: '#categories',
data: {
offset: '',
limit:'',
place: '',
category: '',
inventory: '',
name: '',
city: '',
district: '',
},
methods: {
prefetch: function() {
var filter = {};
if (this.category != '')
filter['category'] = this.category;
if (this.inventory != '')
filter['inventory'] = this.inventory;
if (this.name != '')
filter['name'] = this.name;
if (this.city != '')
filter['city'] = this.city;
if (this.district != '')
filter['district'] = this.district;
if (this.place != '')
filter['place'] = this.place;
//Here I need to provide offset and limit
filter['limit'] = this.limit;
filter['offset'] = this.offset.
if (this.content !== false)
this.content.abort()
this.content = $.ajax({
'url': '/filter/',
data: filter,
dataType: "JSON",
type: "POST",
success: function(e) {
window.searchContent.vector = e.data;
console.log(e);
}
})
}
}
})
</script>
So based on selection of pages in pagination, How can I able to send the corresponding offset value, Please help me to have a solution. I haven't done pagination before
If I select 1, i need to send offset as 50, if 2-100. if 3-150 and so on, I have given in an href IS IT CORRECT.
How can I able to implement easily

Why Does a Template That Renders for One User Not Render For Another User?

New Meteor User.
Wanting to modify the leaderboard example for a story sizing tool where members in a team can rate a story simultaneously.
Very similar to leaderboard, but want to add a flag/event/button for an admin user to be able to turn on and off the leaderboard displayed.
Here is my feeble attempt at this -
// Set up a collection to contain member information. On the server,'
// it is backed by a MongoDB collection named "members".
Members = new Meteor.Collection("members");
Flags = new Meteor.Collection("Flags");
if (Meteor.isClient) {
Meteor.startup(function() {
Session.set("viewall", false);
});
Template.leaderboard.members = function () {
if (Session.get("viewall"))
{
return Members.find({}, {sort: {score: -1, name: 1}});
}
};
Template.size.members = function() {
return Members.find({}, {sort: {name: 1}});
};
Template.size.events ({
'click input.submit': function(){
var memname = document.getElementById('select_member').value;
//alert(memname);
var member = Members.findOne({_id: memname});
if(member._id)
{
Session.set("selected_player", member._id);
//alert(member.name);
}
var memsize = document.getElementById('select_size').value;
alert(memsize);
Members.update(Session.get("selected_player"), {$set: {score: memsize}});
}
});
Template.leaderboard.isAdmin = function() {
var member=Members.findOne(Session.get("selected_player"));
var memtype = member.utype;
if (memtype=== "admin")
{
return true;
}
else
{
return false;
}
};
Template.leaderboard.selected_name = function () {
var member = Members.findOne(Session.get("selected_player"));
return member && member.name;
};
Template.leaderboard.viewAll = function() {
var flag = Flags.findOne({name:"showAll"});
if (flag)
{
alert("View All flag set for current user : " + flag.value);
return flag && flag.value;
}
else return false;
};
Template.leaderboard.selected_size = function () {
var member = Members.findOne(Session.get("selected_player"));
return member && member.score;
};
Template.member.selected = function () {
return Session.equals("selected_player", this._id) ? "selected" : '';
};
Template.leaderboard.events({
'click input.inc1': function () {
alert('setting it to 1');
updatePrevScore();
// Members.find({_id: Session.get("selected_player")}).foreach(function(doc){
// doc.prev_score = doc.score;
// Member.save(doc);
// });
//Members.update(Session.get("selected_player"), {$set: {prev_score: score}});
Members.update(Session.get("selected_player"), {$set: {score: 1}});
},
'click input.inc2': function () {
updatePrevScore();
Members.update(Session.get("selected_player"), {$set: {score: 2}});
},
'click input.inc3': function () {
updatePrevScore();
Members.update(Session.get("selected_player"), {$set: {score: 3}});
},
'click input.inc5': function () {
updatePrevScore();
Members.update(Session.get("selected_player"), {$set: {score: 5}});
},
'click input.inc8': function () {
updatePrevScore();
Members.update(Session.get("selected_player"), {$set: {score: 8}});
},
'click input.inc13': function () {
updatePrevScore();
Members.update(Session.get("selected_player"), {$set: {score: 13}});
},
'click input.inc20': function(){
updatePrevScore();
Members.update(Session.get("selected_player"),{$set: {score:20}});
},
'click input.reset': function(){
if (confirm('Are you sure you want to reset the points?')) {
resetScores();
}
},
'click input.showAll': function() {
setFlag();
},
'click input.hideAll': function() {
resetFlag();
}
});
Template.member.events({
'click': function () {
Session.set("selected_player", this._id);
}
});
function resetFlag() {
Meteor.call("resetFlag", function(error, value) {
Session.set("viewall", false);
});
};
function setFlag() {
Meteor.call("setFlag", function(error, value) {
Session.set("viewall", true);
});
};
function resetScores() {
//alert('resetting scores');
Members.find().forEach(function (member) {
Members.update(member._id, {$set: {prev_score: member.score}});
Members.update(member._id, {$set: {score: 0}});
});
Session.set("selected_player", undefined);
};
function updatePrevScore() {
//alert('resetting scores');
Members.find().forEach(function (member) {
if (member._id === Session.get("selected_player"))
{
Members.update(member._id, {$set: {prev_score: member.score}});
Members.update(member._id, {$set: {score: 0}});
}
});
};
}
// On server startup, create some members if the database is empty.
if (Meteor.isServer) {
Members.remove({});
Meteor.startup(function () {
if (Members.find().count() === 0) {
var names = ["Member 1",
"Member 2",
"Member 3",
"Member 4",
"Member 5"
];
var type;
for (var i = 0; i < names.length; i++)
{
if (i===0)
type = "admin";
else
type="user";
Members.insert({name: names[i], score: 0, prev_score:0, utype:type});
}
}
else resetScores();
if (Flags.find().count() === 0) {
Flags.insert({name: "showAll", value: false});
}
else Flags.update({name:"showAll"}, {$set: {value:false}});
}
);
Meteor.methods({
setFlag: function() {
Flags.update({name:"showAll"}, {$set: {value:true}});
console.log("Updated flag to true");
return true;
},
resetFlag: function() {
Flags.update({name:"showAll"}, {$set: {value:false}});
console.log("Updated flag to false");
return false;
},
}
);
HTML =>
<head>
<title>Story Points Exercise</title>
</head>
<body>
<div id="story_id">
Story Sizing for Story ID: 78972
</div>
<div id="outer">
{{> leaderboard}}
</div>
</body>
<template name="size">
<div class="select_member">
<select id="select_member">
{{#each members}}
<option value={{_id}}> {{name}} </option>
{{/each}}
</select>
</div>
<div class="select_size">
<select id="select_size"> Select Size:
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=5>5</option>
<option value=8>8</option>
<option value=13>13</option>
<option value=20>20</option>
</select>
</div>
<div class="submitbutton">
<input type="button" class="submit" value="Submit" />
</div>
</template>
<template name="leaderboard">
<div class="leaderboard">
{{#if selected_name}}
<div class="details">
<div class="name">{{selected_name}}</div>
<div class="size">{{selected_size}}</div>
<div class="details">
<input type="button" class="inc1" value="1 points" />
<input type="button" class="inc2" value="2 points" />
<input type="button" class="inc3" value="3 points" />
<input type="button" class="inc5" value="5 points" />
<input type="button" class="inc8" value="8 points" />
<input type="button" class="inc13" value="13 points" />
<input type="button" class="inc20" value="20 points" />
</div>
{{#if isAdmin}}
<input type="button" class="showAll" value="showAll" />
<input type="button" class="hideAll" value="hideAll" />
<input type="button" class="reset" value="Reset"/>
{{/if}}
{{#if viewAll}}
{{#each members}}
{{> member}}
{{/each}}
{{/if}}
</div>
{{/if}}
{{#unless selected_name}}
{{>size}}
{{/unless}}
</div>
</template>
<template name="member">
<div class="member {{selected}}">
<span class="name">{{name}}</span>
<span class="score">{{score}}</span>
<span class="prevscore">{{prev_score}}</span>
</div>
</template>
Its working on one browser and one user (Admin type is able to enable the viewAll flag for the template to show all members.)
But, not working for mulitple users.
So, if I open a browser, select my name and a story size and I am the admin, I click Submit - I see buttons for changing the story size and to showAll, hideAll and Resetting the leaderbaord.
when I click on showAll, I as admin can see the leaderboard. But another user is not able to see the leaderboard. I verified that the change display event (showAll flag=true) is being received by that user's client.
Any ideas?
I was able to solve this by using a new collection called Views and observing for a specific document called showAll.
The showAll was set to be updated by the admin only.
It was hooked up to the template view with an {{#if}}.

Categories