Reset input on click, vue - laravel

I would like to have my text fields empty when I click "add task" button. How could I achieve that?
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask()">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask() {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
}

It's very simple, in the addTask() just add event as parameter and in the end of the function you write: event.target.reset();
Code:
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
And there:
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask(event) {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
event.target.reset();
}
Hope it works for you ; )

Related

Recover item id in v-for loop

I am trying to build response to comment. Here is what I am trying to do:
I take the comment ID from the v-for loop and put it in a span that is invisible. Then I want to recover the value of id in 'pm' variable In function call have(), then send it to my controller to insert data in DB. But nothing happens and it shows an error that he can recover the id.
this my vue ProjectDeatil.vue:
<div class="form-group" style="display: inline;" >
<form #submit.prevent="ajouterCommentaire()">
<label>Votre Commentaire:</label>
<div class="input-group input-group-sm mb-0">
<input class="form-control form-control-sm" v-model="form.body" type="text" name="body"
:class="{ 'is-invalid': form.errors.has('body') }" placeholder="commenter.." style="width:450px;">
<has-error :form="form" field="body"></has-error>
<div class="input-group-append">
<button type="submit" class="btn btn-success " >Commenter</button>
</div>
</div>
</form>
</div>
<div v-for="comment in comments" :key="comment.id" class=" align-items mt-3">
<span id="pm" :value="comment.id" style="">{{ comment.id }}</span>
<hr>
<span class="badge badge-primary"> {{ comment.comment_user_name }}</span > {{ comment.body }}
<b> <small class="badge badge-success" style="float:right; color:#2d132c " >Posté le {{ comment.created_at || date }} </small></b>
<br>
<button #click="showbtn(comment.id)" class="btn btn-default" >Répondre</button>
<form #submit.prevent="ajouterCommentaireReponse()" v-bind:id="comment.id " class="d-none">
<div class="input-group input-group-sm mb-0">
<input class="form-control form-control-sm " type="text" name="body"
placeholder="commenter.." style="width:450px;">
<div class="input-group-append">
<button type="submit" class="btn btn-success " >Commenter</button>
</div>
</div>
</form>
<hr>
</div>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
</div>
</div>
<!-- /.row -->
<!-- /.row -->
</div>
<!-- /.card-body -->
</div>
</div>
</template>
<script>
export default {
data(){
return{
key: this.$route.params.id,
projets:[],
projet:{
id:'',
name:'',
durre:'',
description:'',
budget:'',
owner:'',
},
membres:[], membre:{
id :'',
membre:'',
projet_id:'',
},
form : new Form({
id:'',
body:'',
user:'',
}),
comments:[],
comment:{
id:'',
body:'',
created_at:''
}
}
},
methods:{
afficherProjets(){
axios.get('/api/getProjects')
.then(({data}) => {this.projets=data.data});
},
afficherMembre(){
axios.get('/api/membreid').then(({data})=> {this.membres =data.data});
},
ajouterCommentaire(){
this.form.post('/api/comments/'+this.key).then(()=>{
this.form.reset()})
},
ajouterCommentaireReponse(){
axios.post('/api/commentsreponse/'+ this.have()).then(()=>{
})
},
afficherComments(){
axios.get('/api/comments').then(({data})=> {this.comments =data.data});
},
showbtn(id){
let element= document.getElementById(id);
element.classList.toggle('d-none');
},
have(){
var key = document.getElementById('pm').value;
return key;
}
},
mounted() {
console.log('Component mounted.')
this.afficherProjets();
this.afficherMembre();
this.afficherComments();
}
}
</script>
this is my function controller:
public function storereply($key){
//$data =$request->all();
$commentaire=Commentaire::find($key);
$commentairereply =new Commentaire;
$commentairereply->user_id= auth()->user()->id;
$commentairereply->body= request('body');
$commentairereply->comment_user_name=$commentaire->user->name;
$commentaire->comments()->save($commentairereply);
}
and this is my route:
Route::post('/commentsreponse/{key}', 'API\CommentController#storereply');
You need to make sure comment.id can actually reach the have function. Simply pass it as an argument to ajouterCommentaireReponse:
<form #submit.prevent="ajouterCommentaireReponse(comment.id)" v-bind:id="comment.id " class="d-none">
Then, you shouldn't need the help function at all:
module.exports = {
methods:{
ajouterCommentaireReponse(commentId){
axios.post('/api/commentsreponse/'+ commentId)
.then(()=>{
// do things
})
},
},
}
</script>

How to set if else statement in script

-I wan't to do like this: if(!editMode) show create page else show update page because my create and edit using same form so I combine it.
-I'm learning online tutorial but the tutorial show create and edit seperately.
-Please Helps and Thank/.\
<template>
<div v-if="!edit">
<h1>Create Post</h1>
<form #submit.prevent="addPost">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button class="btn btn-primary">Create</button>
</div>
</form>
</div>
<div v-else>
<h1>Update Post</h1>
<form #submit.prevent="updatePost">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button class="btn btn-primary">Update</button>
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return {
edit:false,
post:{}
}
},
},
//this is for create
methods: {
addPost(){
let uri = 'http://localhost:8000/post/create';
this.axios.post(uri, this.post).then((response) => {
this.$router.push({name: 'posts'});
});
},
},
//this is for get data before update
created() {
let uri = `http://localhost:8000/post/edit/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.post = response.data;
});
},
//this is for update post
updatePost() {
let uri = `http://localhost:8000/post/update/${this.$route.params.id}`;
this.axios.post(uri, this.post).then((response) => {
this.$router.push({name: 'posts'});
});
}
</script>
**I also set this in my app.js**
{
name: 'create',
path: '/create',
component: PostForm,
props: {editMode: false}
},
{
name: 'edit',
path: '/edit/:id',
component: PostForm,
props: {editMode: true}
}
My Error--->when I press edit btn show create page and using addPost function.
Result--> how to use if else to solve this.... Sorry I'm rookie in programming.
I believe you can simply have the js figure out the add or update.
<template>
<div>
<h1 v-if="!edit">Create Post</h1>
<h1 v-else>Update Post</h1>
<form #submit.prevent="postSomething">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button v-if="!edit" class="btn btn-primary">Create</button>
<button v-else class="btn btn-primary">Update</button>
</div>
</form>
</div>
</template>
and the js:
methods: {
postSomething(){
if(!this.edit){
this.addPost()
}else{
this.updatePost()
}
},
addPost(){
console.log('should add')
},
updatePost(){
console.log('should update')
}
}

VueJs: How to create a select where options come from a query to other model

I'm new on VueJs and I don't know why I have the following problem:
I'm creating a view called Owners.vue where I show pub owners. In UpdateProfile.vue I show the owner data and here is where I have my problem: I'd like to build a select where the options are the possible pubs stored in my table "pubs":
My vue component is as follows:
UpdateProfile.vue
<template>
<confirm title="Edit User" ok="Save user" :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="User name" v-model="data.name">
</div>
</div>
<div class="field">
<label class="label">Lastname</label>
<div class="control">
<input class="input" type="text" placeholder="last name" v-model="data.lastname">
</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>
<!--Owner Pubs-->
<div class="field">
<label class="label">Pubs</label>
<div v-for="pub in data.userPubsOwned" class="control">
<input class="input" type="text" placeholder="Pub tapps" v-model="pub.name">
<div class="button is-danger" #click="deletePubFromOwner(pub.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<!--Owner Pubs-->
<!--Add Pubs to Owner-->
<div class="field">
<label class="label">Add new Pub</label>
<div class="select">
<select v-model="pubs">
<option v-for = "pub in pubs" :value="pub.id" >{{pub.name}}</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addPubToOwner()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Tapp</span>
</div>
</div>
<!--Add Pubs to Owner-->
</confirm>
import User from "../../models/user";
export default {
props: {
show: Boolean,
data: Object,
},
data() {
return {
selected: null,
data: new User(),
pubs: [],
pub: new Pub(),
}
},
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;
},
addPubToOwner(){
this.api.post('/owners/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deletePubFromOwner(ownerpub) {
this.api.delete('/owners/' + this.data.id + '/' + ownerpub).then(response => {
this.data = response.data;
});
},
}
}
I just need to show all the pubs stored in my table pub...do I have to create a function? And how it would be?
Thanks a lot for your help!!
Yes, create a method in the mounted() section. I use a similar process to show all of the flavors/prices of a product in a shopping cart. Here is my code that you can use and hopefully extrapolate your answer from:
Mounted function to load upon vue mount
mounted: function() {
this.getPrice();
},
getPrice() function:
getPrice: function(){
axios.post('/getproductinfo', this.$data.model)
.then((response) => {
console.log(response);
this.display_name = response.data.display_name;
this.price = '$' + response.data.price;
})
.catch(error => {
this.errors.record(error.response.data.errors);
});
},
And finally the code in your view blade file
<select class="centerSelect" v-show="!loading && ordering" ref="quantitySelect" v-model="model.id" name="code_id" #change="getPrice">
#foreach ($code as $item)
<option value="{{$item->id}}">{{$item->display_name}}</option>
#endforeach
</select>

cannot insert data into vue select sent from laravel

This is the vuejs component for editing song info. the problem here is with tags.I cannot show the tags of the song in vue select for editing.
<template>
<div>
<a data-toggle="modal" :data-target="'#EditModal'+ modalid" #click="select(song)"><span title="edit" class="glyphicon glyphicon-pencil" ></span></a>
<a class=""><span title="delete" class="glyphicon glyphicon-trash"></span></a>
<!-- Modal for editing song tracks-->
<div class="modal fade" :id="'EditModal'+ modalid" tabindex="-1" role="dialog" aria-labelledby="EditModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="EditModalLabel">Edit Song</h5>
<button type="button" class="close" ref="closemodal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form ref="uploadform">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<button type="button" #click="browseImage" class="btn btn-md btn-default">Choose image:</button>
<div id="image_previews">
<img ref='image' class="" v-bind:src="image" width="200px" height="200px" >
<input class="form-control-file" ref="imageinput" type="file" name="feature_image" #change="showImage($event)">
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<label for="title">Song Title:</label>
<input type="text" v-model="esong.title" class="form-control" required maxlength="255">
</div>
<div class="form-group">
<label for="genre"> Genre (tag atleast one) </label>
<v-select :placeholder="'choose tag'" v-model="tagids" label="name" multiple :options="tags"></v-select>
</div>
<div class="form-group">
<label for="upload_type">Song Upload Type</label>
<select name="upload_type" v-model="esong.upload_type" class="form-control">
<option value="public">public( free )</option>
<option value="private">private( for sale )</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Description:</label>
<textarea class="form-control" id="message-text" v-model="esong.song_description"></textarea>
</div>
<div class="form-group" v-if="private">
<label for="upload_type">Song price</label>
<input type="text" v-model="esong.amount" class="form-control" required maxlength="255">
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" #click="edit">Save</button>
</div>
</div>
</div>
</div><!-- end of modal -->
</div>
</template>
<script>
import vSelect from 'vue-select'
export default {
props: ['song','modalid','index','tags'],
components: {vSelect},
mounted() {
},
watch: {
tagids() {
console.log('changed tagids value');
// this.value = this.tagsid;
}
},
computed: {
private() {
if(this.esong.upload_type == 'private') {
return true;
}
return false;
},
},
methods: {
select(song) {
console.log(song.title);
this.getTagIds(song);
},
edit() {
let formData = new FormData();
formData.append('title', this.esong.title);
formData.append('img', this.esong.img);
formData.append('description', this.esong.song_description);
formData.append('upload_type', this.esong.upload_type);
formData.append('amount', this.esong.amount);
formData.append('tags', JSON.stringify(this.tagids));
formData.append('_method', 'PUT');
axios.post('/artist/songs/' + this.esong.id, formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response =>{
this.$refs.closemodal.click();
toastr.success('successfully edited song.');
this.$emit('update', {song:this.esong,index:this.index});
}).catch(error => {
console.log(error);
});
},
getTagIds(song) {
axios.post('/gettagids', song ).then(response =>{
this.tagids = response.data;
}).catch(error =>{
console.log(error);
});
},
browseImage() {
this.$refs.imageinput.click();
},
showImage(event) {
this.esong.img = event.target.files[0];
this.image = URL.createObjectURL(event.target.files[0]);
}
},
data() {
return {
esong: this.song,
tagids: {id:'', name:'', label:''},
name:'name',
image:this.song.image
}
}
}
</script>
<style scoped>
input[type="file"] {
display: none;
}
#image_previews {
border-radius: 5px;background-color: whitesmoke; width: 200px; height: 200px;
}
.btn{
border-radius: 0px;
}
</style>
here I cannot get the selected value that was inserted in my table. I wanted to show the tagged values for a song. I am able to get all object of tagged songs from axios post request but v-select doesn't shows the selected value retrieved from a table.
the object received from laravel is similar to the object provided in options which work well with v-select..but it doesn't show the same structure object provided to v-model..or should I provide other props. the document for vue select has not mentioned any of these things

how to highlight invalid section — twitter bootstrap/jquery/validate plugin

I have a form in twitter bootstrap:
<div class="form-div">
<form id="fvujq-form1" method="post" action="">
<div class="control-group name">
<fieldset>
<label>Name *</label>
<input type="text" name="name">
</fieldset>
</div>
<div class="control-group email">
<fieldset>
<label>E-Mail *</label>
<input type="text" name="email">
</fieldset>
</div>
<div class="control-group comment">
<fieldset>
<label>Your comment *</label>
<textarea name="comment"></textarea>
</fieldset>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
and this is how I validate it with bassistance Validate plugin:
$(document).ready(function() {
$("#fvujq-form1").validate({
submitHandler:function(form) {
SubmittingForm();
},
success: function(label) {
label.html("✔").addClass("valid");
},
onfocusout: function(element) { $(element).valid(); },
focusInvalid: false,
highlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).removeClass('error');
},
errorClass: "help-inline",
errorElement: "strong"
I want to add .error to the div currently validated, but this code adds class to every .control-group occurence, not only validated one :(
thx 4 yr help.
JSFiddler Example
This will validate as you leave each field or when you hit the submit button all fields that meet the rules will present errors.
HTML
<form action="" id="fvujq-form1" class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="comment">Comment</label>
<div class="controls">
<input type="text" class="input-xlarge" name="comment" id="comment">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$('#fvujq-form1').validate(
{
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
comment: {
minlength: 2,
required: true
},
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});

Resources