VueJS: Cannot read property 'name' of undefined" - javascript

I cannot understand and find a solution to this problem. I'm trying to edit a pub schedule using an edit form:
pubs/UpdateProfile.vue
<template>
<confirm title="Edit Pub" ok="Save pub" :show="show"
v-on:save="save"
v-on:close="close">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Pub name" v-model="data.name">
</div>
</div>
<div class="field">
<label class="label">Address</label>
<div class="control">
<input class="input" type="text" placeholder="Pub address" v-model="data.address">
</div>
</div>
<div class="field">
<label class="label">Latitude</label>
<div class="control">
<input class="input" type="number" placeholder="Pub latitude" v-model="data.latitude">
</div>
</div>
<div class="field">
<label class="label">Longitude</label>
<div class="control">
<input class="input" type="number" placeholder="Pub longitude" v-model="data.longitude">
</div>
</div>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input class="input" type="email" placeholder="email" v-model="data.email">
</div>
</div>
<div class="field">
<label class="label">Phone</label>
<div class="control">
<input class="input" type="text" placeholder="Pub phone" v-model="data.phone">
</div>
</div>
<div class="field">
<label class="label">Description</label>
<div class="control">
<input class="input" type="text" placeholder="Pub description" v-model="data.description">
</div>
</div>
<div class="field">
<label class="label">Web</label>
<div class="control">
<input class="input" type="text" placeholder="Pub web" v-model="data.web">
</div>
</div>
<div class="field">
<label class="label">Twitter</label>
<div class="control">
<input class="input" type="text" placeholder="Pub twitter" v-model="data.twitterUrl">
</div>
</div>
<div class="field">
<label class="label">Facebook</label>
<div class="control">
<input class="input" type="text" placeholder="Pub facebook" v-model="data.facebookUrl">
</div>
</div>
<div class="field">
<label class="label">Instagram</label>
<div class="control">
<input class="input" type="text" placeholder="Pub instagram" v-model="data.instagramUrl">
</div>
</div>
<!--Tapps-->
<div class="field">
<label class="label">Tapps</label>
<div v-for="tapp in data.tappsDisplayed" class="control">
<input class="input" type="text" placeholder="Pub tapps" v-model="tapp.name">
<div class="button is-danger" #click="deleteTappFromPub(tapp.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<div class="field">
<label class="label">Añadir Tapps</label>
<div class="select">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option :value ="1">CRAFT_BEER</option>
<option :value ="2">SOMETHING_SWEET</option>
<option :value ="3">FREE_TAPA</option>
<option :value ="4">PUB_TERRACE</option>
<option :value ="5">WIFI</option>
<option :value ="6">FOOTBALL_MATCHES</option>
<option :value ="7">ANIMALS_ALLOWED</option>
<option :value ="8">CREDIT_CARD_PAYMENT</option>
<option :value ="9">GLUTEN_FREE</option>
<option :value ="10">VEGETARIAN_DIET</option>
<option :value ="11">BREAKFAST</option>
<option :value ="12">BRUNCH</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addTappToPub()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Tapp</span>
</div>
</div>
<!--Tapps-->
<!--Beers-->
<div class="field">
<label class="label">Beers</label>
<div v-for="beer in data.beersDisplayed" class="control">
<input class="input" type="text" placeholder="Pub beers" v-model="beer.name">
<div class="button is-danger" #click="deleteBeerFromPub(beer.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<div class="field">
<label class="label">Añadir Beers</label>
<div class="select">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option :value ="1">ESTRELLA_GALICIA</option>
<option :value ="2">MAHOU</option>
<option :value ="3">SAN_MIGUEL</option>
<option :value ="4">HEINEKEN</option>
<option :value ="5">OTHERS</option>
<option :value ="6">AMSTEL</option>
<option :value ="7">ESTRELLA_DAMN</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addBeerToPub()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Beer</span>
</div>
</div>
<!--Beers-->
<!--Brands-->
<div class="field">
<label class="label">Brands</label>
<div v-for="brand in data.brandsDisplayed" class="control">
<input class="input" type="text" placeholder="Pub brands" v-model="brand.name">
<div class="button is-danger" #click="deleteBrandFromPub(brand.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<div class="field">
<label class="label">Añadir Brands</label>
<div class="select">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option :value ="1">COCA_COLA</option>
<option :value ="2">SCHWEPPES</option>
<option :value ="3">PEPSICOLA</option>
<option :value ="4">GIN_TONIC</option>
<option :value ="5">SIDRA_EL_LADRON</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addBrandToPub()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Brand</span>
</div>
</div>
<!--Brands-->
<!--Pub Photo-->
<div class="field">
<label class="label">Pub photo</label>
<div class="input-group">
<span class="input-group-addon">Imagen:</span>
<input class="form-control" type="file" v-on:change="updatePhoto">
</div>
<br>
</div>
<!--Pub Photo-->
<!--Set pub schedules-->
<div class="field">
<label class="label">Schedules</label>
<div v-for="schedule in data.schedulesDisplayed" class="control">
<div class="container">
<div class="field">
<label class="label">Week Day: {{schedule.week_day}}</label>
</div>
<div class="row">
<div class="col">
<div class="row">
Opening Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.opening_time">
</div>
<div class="row">
<div class="buttons is-left">
<div class="button is-info" #click="updateOpeningTime(schedule)">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Save</span>
</div>
<div class="button is-danger" #click="deleteOpeningTime(schedule.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
</div>
</div>
<div class="col">
<div class="row">
Closing Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.closing_time">
</div>
<div class="row">
<div class="buttons is-left">
<div class="button is-info" #click="updateClosingTime(schedule.id)">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Save</span>
</div>
<div class="button is-danger" #click="deleteClosingTime(schedule.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
<br>
</div>
<!--Set pub schedules-->
<!--Set pub as suggested/non-suggested-->
<div class="field">
<label class="checkbox">
Set pub as suggested <input type="checkbox" v-model="data.suggested">
</label>
</div>
<!--Set pub as suggested/non-suggested-->
</confirm>
<script>
import Pub from "../../models/pub";
export default {
data() {
return {
selected: null,
data: new Pub(),
}
},
props: {
show: Boolean,
data: Object,
},
computed: {
},
methods: {
save() {
this.$emit('save', this.data);
},
close() {
this.$emit('close');
},
hasRootPermissionsAndIsNotRoot() {
return this.CONSTANTS.hasRootPermissions() &&
this.data.permissions !== this.CONSTANTS.ROOT_USER.permissions;
},
deleteTappFromPub(pubtapp) {
this.api.delete('/pubtapps/' + this.data.id + '/' + pubtapp).then(response => {
this.data = response.data;
});
},
addTappToPub(){
this.api.post('/pubtapps/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deleteBeerFromPub(pubbeer) {
this.api.delete('/pubbeers/' + this.data.id + '/' + pubbeer).then(response => {
this.data = response.data;
});
},
addBeerToPub(){
this.api.post('/pubbeers/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deleteBrandFromPub(pubbrand) {
this.api.delete('/pubbrands/' + this.data.id + '/' + pubbrand).then(response => {
this.data = response.data;
});
},
addBrandToPub(){
this.api.post('/pubbrands/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
updateOpeningTime(schedule){
this.api.put('/pubschedules/' + this.data.id, schedule).then(response => {
data = response.data;
});
},
updatePhoto(event) {
let photo=null;
if(event && event.target && event.target.files.length){
photo = event.target.files[0];
}
this.api.multipart('/pubphoto/' + this.data.id, {'photo': photo});
}
}
}
and where I write my updateOpeningTime function:
updateOpeningTime(schedule){
this.api.put('/pubschedules/' + this.data.id + '/' + schedule).then(response => {
this.data = response.data;
});
},
In my controller:
PubsController.php
public function updateOpeningTime(Pub $pub)
{
json_die("Hola");
json_die($pub->id);
Schedule::where(['pub_id', $pub->id])->update(['opening_time' => request()->all()]);
}
pub.js
export default class Pub {
constructor() {
this.id = null;
this.name = null;
this.schedulesDisplayed = null;
}
};
schedulesDisplayed comes from a relation between Pub and Schedule models (pubSchedules: 1pub x N schedules):
/**
* #return \Illuminate\Database\Eloquent\Collection
*/
public function getSchedulesDisplayedAttribute()
{
return $this->pubSchedules()->get();
}
When I click on my Save button after editing I can display the message "Hola" that I have in my controller, but I have the following errors that doesn't allow me to continue developing my form:
app.js:56802 [Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
found in
---> <UpdateProfile> at
resources/assets/js/components/pubs/UpdateProfile.vue
<Pubs> at resources/assets/js/components/Pubs.vue
<Root>
I cannot find something called 'name' that I'm using in my function and .vue view. What am I doing wrong?

Your updateOpeningTime function should be something like this:
updateOpeningTime(schedule) {
var instance = this;
this.api.put('/pubschedules/' + this.data.id, schedule).then(response => {
instance.data = response.data;
});
}
Otherwise inside the "then" of the API call the word this is not referencing to the instance of your component.

Related

how to add validation in javascript on form so that it should not append form when last row is empty (should not create another row untill all fields)

function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div class="col-md-2">
<label>Product Variants</label>
<a class="btn btn-primary" id="add_variant" onclick="add_variant()"><i class="fa fa-plus"></i> add Variant</a>
</div>
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</div>
<div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</template>
</div>
i am new to java script i am trying to add some validations on my add product form in which i am trying to perform some append function in whixh i want to append a div but if the previous row is empty then it should not add/append new row but while doing so it just check validation for the 1st row when i add 2 nd add try to add 3rd it shows error
will please anybody help me to solve this,here is my code
JS:
function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<button class="btn btn-danger"><i class="fa fa-
trash"></i></button>
</div>
<!--further fields-->
</div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i>
</button>
<!--further fields->
</div>
</div>
</template>
`
Here is the code:
const addVariant = document.getElementById("add_variant");
const productDescription = document.getElementById("product_description");
const errorAlert = document.querySelector(".alert");
const template = `<div class="row my-4 p-3 rounded productTemp">
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger btnDelete">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
`;
function addAlert(message) {
errorAlert.classList.add("show");
errorAlert.innerHTML = message;
setTimeout(() => {
errorAlert.classList.remove("show");
}, 3000);
}
addVariant.addEventListener("click", function() {
const productTemp = document.querySelectorAll(".productTemp");
const lastElement = productTemp[productTemp.length - 1];
const thickness = lastElement.querySelector('[name="thickness"]');
const thicknessUnit = lastElement.querySelector('[name="thickness_unit"]');
const productQty = lastElement.querySelector('[name="product_qty"]');
const productPrice = lastElement.querySelector('[name="product_cost_price"]');
const productUnit = lastElement.querySelector('[name="product_unit"]');
const productColor = lastElement.querySelector('[name="product_color"]');
if (
thickness.value !== "" &&
thicknessUnit.value !== "" &&
productQty.value !== "" &&
productPrice.value !== "" &&
productUnit.value !== "" &&
productColor.value !== ""
) {
productDescription.insertAdjacentHTML("beforeend", template);
} else {
addAlert("Fields can not be empty! 😑");
}
});
.productTemp {
background-color: #2c3035;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<body class="bg-dark text-white">
<div class="container mt-5 bg-dark text-white">
<div class="alert alert-danger alert-dismissible fade mb-5" role="alert"></div>
<div class="col-md-2 mb-4">
<label class="mb-2">Product Variants</label>
<a class="btn btn-primary" id="add_variant">
<i class="fa fa-plus"></i> add Variant
</a>
</div>
<div id="product_description">
<div class="row my-4 p-3 rounded productTemp">
<div class="col-sm-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>

How to update the cart with ajax json response

I am adding items to cart with ajax request but i don't know how to update the cart with ajax response.
This is my index.blade.php code from where i am adding items to cart with some inputs in cart:
<form id="product-1">
#csrf
<div class="modal-body cart-addon" style="margin-top: 20px">
<div class="food-item white">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="item-img pull-left">
<a class="restaurant-logo pull-left" href="#"><img id="image"/> </a>
</div>
<div class="rest-descr">
<h6><input id="name" name="name" style="width: 200px; border: none; margin-top: 15px" readonly></h6>
</div>
</div>
<!-- end:col -->
<div class="col-xs-6 col-sm-2 col-lg-2 text-xs-center"> <span class="price pull-left">$<input id="price" name="price" style="width: 50px; border: none" readonly></span></div>
<div class="col-xs-6 col-sm-4 col-lg-4">
<div class="row no-gutter">
<div class="form-group">
<select class="form-control" id="quantity" name="quantity" required>
<option selected="selected" disabled="disabled" value="">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<select class="form-control" id="spice" name="spice" required>
<option selected="selected" disabled="disabled" style="font-size: 14px" value="">Choose Spice</option>
<option value="Mild" style="font-size: 14px">Mild</option>
<option value="Medium" style="font-size: 14px">Medium</option>
<option value="Hot" style="font-size: 14px">Hot</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="naan" name="naan" required>
<option selected="selected" disabled="disabled" style="font-size: 14px" value="">Choose Naan</option>
<option value="No Naan" style="font-size: 14px">No Naan</option>
<option value="Naan" style="font-size: 14px">Naan</option>
<option value="Garlic Naan" class="red">Garlic Naan +$1.00</option>
<option value="Roti" style="font-size: 14px">Roti</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="rice" name="rice" required>
<option selected="selected" disabled="disabled" style="font-size: 14px" value="">Choose Lunch Rice</option>
<option value="No Rice" style="font-size: 14px">No Rice</option>
<option value="Rice" style="font-size: 14px">Rice</option>
</select>
</div>
<input class="form-control" name="instructions" id="instructions" placeholder="Instruction"/>
</div>
<div class="row">
<div class="col-md-7"></div>
<div class="col-md-2">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div class="col-md-3">
<input hidden name="products_id" id="products_id">
<button type="submit" class="btn theme-btn">Add to cart</button>
</div>
</div>
</div>
</form>
Ajax Request:
<script>
$("#product-1").submit(function (e){
e.preventDefault();
let quantity = $("#quantity").val();
let spice = $("#spice").val();
let naan = $("#naan").val();
let rice = $("#rice").val();
let instructions = $("#instructions").val();
let products_id = $("#products_id").val();
let _token = $("input[name=_token]").val();
$.ajax({
url: "{{route('product.addToCart')}}",
type: "get",
data:{
products_id:products_id,
quantity:quantity,
spice:spice,
naan:naan,
rice:rice,
instructions:instructions,
_token:_token
},
beforeSend: function() {
},
success:function(response)
{
$("#product-1")[0].reset();
$('#product-modal').modal('hide');
$('#product-modal').trigger("click");
}
})
});
and this is my controller:
public function getAddToCart(Request $request)
{
$products = Products::find($request->products_id);
$quantity = $request->input('quantity');
$instructions = $request->input('instructions');
$spice = $request->input('spice');
$naan = $request->input('naan');
$rice = $request->input('rice');
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
for ($i = 1; $i <= $quantity; $i++)
{
if ($naan == "Garlic Naan"){
$cart->garlic_add($products, $products->id, $instructions, $spice, $naan, $rice);
} else
$cart->add($products, $products->id, $instructions, $spice, $naan, $rice);
}
$request->session()->put('cart', $cart);
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
$request->session()->put('cart', $cart);
return back();
return redirect('/');
}
This is my blade part where i am showing cart.
#if(Session::has('cart'))
#foreach($carts as $product)
<div class="order-row bg-white">
<div class="widget-body">
<div class="title-row">{{ $product['item']['name'] }}
<form id="reduceProduct">
<input name="id" id="id" value="{{$product['item']['id']}}">
<button type="submit" style="background-color: transparent; border: 0;"><i class="fa fa-trash pull-right" style="color: #FF3300"></i></button>
</form>
</div>
<div class="title-row">{{ $product['instructions'] }}</div>
<div class="title-row">{{ $product['spice'] }}</div>
#if(!empty($product['rice']))
<div class="title-row">{{ $product['rice'] }}</div>
#endif
<div class="form-group row no-gutter">
<div class="col-xs-8">
<select class="form-control b-r-0" id="exampleSelect1">
<option>Size SM</option>
<option>Size LG</option>
<option>Size XL</option>
</select>
</div>
<div class="col-xs-4">
<input class="form-control" type="number" value="{{ $product['qty'] }}" id="example-number-input">
{{ $product['item']['price'] }}
{{ $product['price'] }}
</div>
</div>
</div>
</div>
#endforeach
<!-- end:Order row -->
<div class="widget-delivery clearfix">
<form>
<div class="col-xs-6 col-sm-12 col-md-6 col-lg-6 b-t-0">
<label class="custom-control custom-radio">
<input id="radio4" name="radio" type="radio" class="custom-control-input" checked=""> <span class="custom-control-indicator"></span> <span class="custom-control-description">Delivery</span> </label>
</div>
<div class="col-xs-6 col-sm-12 col-md-6 col-lg-6 b-t-0">
<label class="custom-control custom-radio">
<input id="radio3" name="radio" type="radio" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">Takeout</span> </label>
</div>
</form>
</div>
<div class="widget-body">
<div class="price-wrap text-xs-center">
<p>TOTAL</p>
<h3 class="value"><strong>$ 25,49</strong></h3>
<p>Free Shipping</p>
<button onclick="location.href='checkout.html'" type="button" class="btn theme-btn btn-lg">Checkout</button>
</div>
</div>
Can any help me with the code that how can i update the cart with ajax response.
ThankYou

Generateing dynamic id attribute for radio and checkboxes in vue

I am adding a vue component on button click. Its adding new form element with checkbox and radio button which contain id with for element of . How to assign a new Id to checkboxes and radio buttons every time I add a new component.
I tried passing numeric values to the id and for attributes but it doesn't work
Vue.component('persons-phone', {
props: ['index'],
template: `
<div class="row person_phone_wrapper">
<div class="col-md-4">
<div class="form-group">
<label for="person_phone">Phone Number : <span class="danger">*</span></label>
<input type="tel" class="form-control required" name="person_phone[]">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="c-inputs-stacked">
<br><br>
<input type="checkbox" id="verified_number_#{{ index }}" name="verified_phone[]">
<label for="verified_number_#{{ index }}" class="block">Verified</label>
</div>
</div>
</div>
<div class="col-md-4">
<div>
<br><br>
<input name="phone_status[]" type="radio" class="with-gap" id="radio_#{{ index }}" />
<label for="radio_#{{ index }}">Active</label>
<input name="phone_status[]" type="radio" class="with-gap" id="radio_#{{ index + 1 }}"/>
<label for="radio_#{{ index + 1 }}">Inactive</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="remove_person_phone"> </label><br>
<button type="button" class="btn btn-danger btn-sm" #click="$emit('remove')">
<i class="fa fa-close"></i> Remove
</button>
</div>
</div>
</div>
`,
})
var app = new Vue ({
el: '#app',
data: {
personsPhoneCount: [1],
currentPhoneIndex: 1
},
methods: {
deletePersonsPhone: function(index){
this.personsPhoneCount.splice(index,1)
},
addPersonsPhone: function(){
index = this.currentPhoneIndex + 1;
this.currentPhoneIndex = index;
this.personsPhoneCount.push(index);
}
},
computed: {
}
})
<persons-phone v-for="(pPC, index) in personsPhoneCount" #remove="deletePersonsPhone(index)" :num="currentPhoneIndex">
</persons-phone>
Doing this solved my problem
Vue.component('persons-phone', {
props: {
index: {
type: Number,
required: true
},
},
template: `
<div class="row person_phone_wrapper">
<div class="col-md-4">
<div class="form-group">
<label for="person_phone">Phone Number: <span class="danger">*</span></label>
<input type="tel" class="form-control required" name="person_phone[]">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="c-inputs-stacked">
<br><br>
<input type="checkbox" :id="checkbox" name="verified_phone[]">
<label :for="checkbox" class="block">Verified</label>
</div>
</div>
</div>
<div class="col-md-4">
<div>
<br><br>
<input :name="radio" type="radio" class="with-gap" :id="radio1" />
<label :for="radio1">Active</label>
<input :name="radio" type="radio" class="with-gap" :id="radio2"/>
<label :for="radio2">Inactive</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="remove_person_phone"> </label><br>
<button type="button" class="btn btn-danger btn-sm" #click="$emit('remove')">
<i class="fa fa-close"></i> Remove
</button>
</div>
</div>
</div>
`,
data: function() {
return {
radio: 'phone_status['+this.index+']',
radio1: 'radio_' + this.index,
radio2: 'radio_' + this.index + '_' + this.index,
checkbox: 'verified_number_'+ this.index,
}
}
})

How to add multiple sections[] and subfeilds[] inside fields[] in vue js html?

How to add multiple sections[] and subfields[] inside fields[]?
My HTML form:
<div class="col-md-12 mr-auto" id="regBox">
<form class="form" method="POST" v-on:submit.prevent="handelSubmit($event);">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">room</i>
</span>
</div>
<select class="form-control" v-model="type" name="type" required="">
<option value="" selected disabled hidden>Choose Type here</option>
<option value="option">option</option>
<option value="text">text</option>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">account_circle</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Rule Name" v-model="text" required="" maxlength="20">
</div>
</div>
<div class="card-content" v-for="(bok, index) in feilds" :key="index">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Name..." v-model="bok.name" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Section..." v-model="bok.sections[0]" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Name..." v-model="bok.subfeilds[0].name" required="">
</div>
</div>
<h3>The JSON value of <code>bok</code></h3>
<textarea rows="3" cols="75%" readonly>{{ JSON.stringify(bok) }}</textarea>
</div>
<a #click="addNewRules">Add Another Rule</a>
<div class="text-center">
<button class="btn btn-primary btn-round">Get Started</button>
</div>
</form>
</div>
VueJS code:
regBox = new Vue({
el: "#regBox",
data: {
type:'',
text:'',
feilds : [{
name : null,
sections:[null],
subfeilds : [{name:null}],
}],
},
methods: {
addNewRules: function() {
this.feilds.push({ name : null,
sections:[null],
subfeilds : [{name:null}],
});
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['feilds'] = this.feilds;
data['type'] = this.type;
data['text'] = this.text;
$.ajax({
url: 'http://localhost:4000/add/act/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Registration Success");
}
else {
alert("Registration Failed");
vm.response = e;
}
}
});
return false;
},
},
});
My problem arises when I add fields[]. sections[] should be an array so, how can I add multiple sections inside fields . Also how can I add multiple subfields inside the fields[].
The code provided was perfectly working. The only issue is that I am not able to have multiple sections[] and subfields[], which is required.
<form class="form" method="POST" v-on:submit.prevent="handelSubmit($event);"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">room</i> </span> </div> <select class="form-control" v-model="type" name="type" > <option value="" selected disabled hidden>Choose Type here</option> <option value="option">option</option> <option value="text">text</option> </select> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">account_circle</i> </span> </div> <input type="text" class="form-control" placeholder="Rule Name" v-model="text" maxlength="20"> </div> </div> <div class="card-content" v-for="bok in feilds"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Username..." v-model="bok.name" > </div> </div> <div v-for="child in bok.subfeilds"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Offences..." v-model="child.name" > </div> </div> </div> <a class="btn btn-success" #click="addChild(bok)">Add Offence</a> <div v-for="(secure,index) in bok.sections"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Section..." v-model="bok.sections[index]" > </div> </div> </div> <a class="btn btn-success" #click="addSection(bok)">Add</a> <h3>The JSON value of <code>bok</code></h3> <textarea rows="3" cols="75%" class="form-control" readonly>{{ JSON.stringify(bok) }}</textarea> </div> <a #click="addNewRules">Add Another Rule</a> <div class="text-center"> <button class="btn btn-primary btn-round">Get Started</button> </div> </form>
regBox = new Vue({
el: "#regBox",
data: {
type:'',
text:'',
feilds : [{
name : null,
sections:[],
subfeilds : [{name:null}],
}],
},
methods: {
addNewRules: function() {
this.feilds.push({ name : null,
sections:[],
subfeilds : [{name:null}],
});
},
addChild: function(bok) {
bok.subfeilds.push({});
},
addSection: function(bok) {
bok.sections.push({});
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['feilds'] = this.feilds;
data['type'] = this.type;
data['text'] = this.text;
$.ajax({
url: 'http://localhost:4000/add/act/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Registration Success");
}
else {
alert("Registration Failed");
vm.response = e;
}
}
});
return false;
},
},
});
I have added loops in each case. Just check this was what you expected

Dynamic multiselect feature

I am creating the fields dynamically in HTML using this JS, and in multiselect I'm using bootstrap multiselect here is the code https://bootsnipp.com/snippets/Ekd8P when I click on the add more button it creates the form dynamically.
js code for creating a form dynamically :
$(function() {
// Remove button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-horizontal').remove();
}
);
// Add button
var i = 1;
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-horizontal:first-child').clone();
new_field_group.find('input').each(function() {
if (this.name == 'tags[0]') {
$(this).tagsinput('destroy');
$(this).tagsinput('removeAll');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="form-group"]');
new_container.find(".bootstrap-tagsinput:first").remove();
} else {
$(this).val('');
}
});
new_field_group.find('select').each(function() {
if (this.name == 'addons[0]') {
$(this).multiselect('rebuild');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="multiselect-native-select"]');
new_container.find(".multiselect-native-select > .multi").remove();
} else {
$(this).val('');
}
});
i += 1;
container.append(new_field_group);
}
);
});
and html code for form elements:
<form action="" method="post" novalidate="novalidate" enctype="multipart/form-data">
{{ csrf_field() }}
<div data-role="dynamic-fields">
<div class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Name1" name="Name[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Price" name="Price[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Select Food Type</label>
<div class="col-sm-8">
<select id="select1" class="form-control" name="select[]" required>
#foreach($types as $type)
<option value="{{$loop->iteration}}">{{$type->food_type_name}}</option>
#endforeach
</select>
<p class="help-block" data-toggle="tooltip" data-placement="bottom" title="xyz"><i class="md md-info"></i></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Dish Description</label>
<div class="col-sm-8">
<textarea name="Description[]" id="field-value" class="form-control" rows="1"></textarea>
</div>
</div>
</div>
<div class="col-sm-4 contacts">
<div class="form-group">
<label class="col-sm-3" for="rolename">Add Addons</label>
<div class="col-sm-8">
<select id="dates-field2" class="multiselect-ak form-control" name="addons[0]" id="trigger3" data-role="multiselect" multiple="multiple">
#foreach($addons as $addon)
<option value="{{$addon->addonid}}">{{$addon->addon_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Tags</label>
<div class="col-sm-8">
<input type="text" value="" name="tags[0]" class="form-control" data-role="tagsinput" placeholder="e.g. spicy, healthy" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-4">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="Price2[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-5">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" class="trigger" id="trigger" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields" class="hidden_fields" style="display:none;">
<input type="text" id="hidden_field" name="Price3[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
</div>
<br>
<button class="btn btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove">
Delete Item
</button>
<button class="btn ink-reaction btn-raised btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add">
Add More Items
</button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
<div class="form-group">
<button type="submit" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary" style="margin-top: -62px;margin-left: 160px;">Submit Items</button>
</div>
<!--end .form-group -->
</form>
The issue is that when I click on the add more item it reflects the multiselect dropdown twice as you see in this image.
I want that if I click on the add more item button it restates the multiselect dropdown as in the first state.
see this jsfiddle.net/akshaycic/svv742r7/7 it will clear all your doubt. on click plus button it is not reflect to "none selected" state it will remain in its initial state.
Any leads would be helpful. Thank you in advance.

Categories

Resources