I have a working select box that is sending the selected value to a method on the change event but I have a question with this:
Say I want to send the cat_id value at the time of selection as well (so that I could build an object that relates the cat_id and date within the called method) is there a way to send that cat_id, or any other data, along in that select box change event?
var vm =
new Vue({
el: "#app",
props: {
},
data: {
testing_dates:['2021-11-29', '2021-11-30'],
cat_id: [123]
},
methods: {
testChange(event){
console.log(event.target.value);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li>Category ID: {{ cat_id }}</li>
<li style="list-style: none;">
<select style="width: auto;" #change="testChange($event)">
<option selected disabled>Options</option>
<option v-for="date in testing_dates" :value="date">{{ date }}</option>
</select>
</li>
</div>
You can pass another parameter:
#change="testChange($event, cat_id)"
testChange(event, catId){
console.log(event.target.value, catId);
}
Or access it inside the function:
testChange(event){
console.log(event.target.value, this.cat_id);
}
Related
I'm using vuejs.
Let's say I have select and inside I have multiple options
like this:
<select v-model='line.unit' name='unit[]' required #change='change_unit($event)'>
<option v-for='(unit) in line.units' price='line.price' :value='unit.id'>#{{unit['get_unit_id']['name']}}</option>
<option selected class='selected' price='line.price' v-if='line.smallest_unit' :value='line.smallest_unit.id'>#{{line.smallest_unit['name']}}</option>
</select>
And this is the change_unit method:
change_unit:function($event)
{
}
How can I access the attribute price if I want the value of the selected option? I can get it like this ..
console.log(event.target.value);
But now can I access the price value attribute?
you could tweak the option value binding it to Vue.js
as you can see in this fiddle, which I'll explain here
Consider this HTML
<div id="app">
<select v-model="line.unit" name='unit[]' required>
<option v-for='(unit) in line.units' :value="unit">
{{unit.name}}
</option>
</select>
<h2 v-if="line.unit">
{{line.unit.price}}
</h2>
</div>
As you can see, I'm setting the <option> value binding it to unit, which is each single line.units item object. by doing that, selecting an option will actually set the v-model to unit, instead of an object's attribute
Consider this JS, in which I've created a hypotetic reproduction of your .data.
new Vue({
el: '#app',
data() {
return {
line: {
unit: {},
units: [{
id: 1,
price: 100,
name: 'foo'
},{
id: 2,
price: 200,
name: 'bar'
}]
}
}
}
})
Selecting an option will now show you it's price (I've put a <h2> as a demonstration)
I code an html page with a drop-down list with HTML CSS and VueJS. I want that if I click on a certain option in my drop-down list, it display something in console.
My html code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="js/historique.js"></script>
<title>Historique</title>
</head>
<body>
<select id="selectionMachines" size="1">
<option v-for="todo in todos" v-on:click="action">
{{ todo.libelle }}
</option>
</select>
</body>
</html>
And my JS code :
window.onload = function () {
var machines = new Vue({
el:"#selectionMachines",
data: {
todos: [
{ libelle: "Machine 195", num: 195},
{ libelle: "Machine 196", num: 195}
]
},
methods: {
action: function() {
console.log(this.todo.num);
if (this.todos.num == 195)
console.log("J'ai choisi 195");
}
}
})
}
The action function doesn't work for the moment, undefined is log in console. Any idea ?
The event should be bound to <select>.
The event should pass the $event variable to the function
The options' values should be bound to the options themselves (:value=""). You'll get this value with the $event ($event.target.value)
Even though you literally click on a <select> and the <option>, the event is not click(), but input or change, as it's an input field. This is not VueJS question, but JavaScript.
Your action() method is a function, so if you want it to get executed, then you have to call it with parantheses (action()), and not it's "string value" (action). This is unlike computed in VueJS templates, but VueJS handles the difference.
Pay attention to your todos - both have a num key with value 195 (so you won't see a difference in the console, both will log 195 there), although their label (libelle) implies 195 and 196
You write console.log(this.todo.num); and this.todos.num == 195 in your action() method. I guess you tried to use the single todo item that's selected in the input. The problem with this is that the input (and the todo in todos) only exist in your template, your scripts (like methods) don't know about them - you have to pass the information somehow to those scripts ($event is good for that). If you want to get the whole single todo object to work with, then I suggest find() (or filter() as your num value is not unique).
new Vue({
el: "#selectionMachines",
data: {
todos: [{
libelle: "Machine 195",
num: 195
},
{
libelle: "Machine 196",
num: 195
}
]
},
methods: {
action: function(event) {
console.log(event.target.value)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<select id="selectionMachines" size="1" #change="action($event)">
<option v-for="todo in todos" :value="todo.num">
{{ todo.libelle }}
</option>
</select>
Try this:
<option v-for="todo in todos" #click="action(todo)">
{{ todo.libelle }}
</option>
action(todo) { if (todo.num === 195) console.log("J'ai choisi 195"); }
Yes me again!
This is my project
I want to pull the data from the json file when I fill in the required fields and press the button.
For example, let's write the developer part to the jobs section. then select istanbul as an option and click Find!.
var app = new Vue({
el: "#app",
data: {
founded: [],
search: ""
},
created() {
fetch("job.json")
.then(res => {
return res.json();
})
.then(res => {
this.founded = res.items;
});
},
computed:{
filteredFounded: function(){
return this.founded.filter((items)=> {
return items.positionName.match(this.search)
});
}
}
});
<div class="header">
<h4>Get Job</h4>
</div>
<div id="app" class="nested">
<div class="card w-50">
<div class="search">
<input type="text" class="job" v-model="search" placeholder="Job...">
<select name="" class="city" id="">
<option value="Seçiniz">Seçiniz</option>
<option value="İstanbul">İstanbul</option>
<option value="Ankara">Ankara</option>
<option value="İzmir">İzmir</option>
<option value="Çanakkale">Çanakkale</option>
</select>
</div>
<div class="find">
<button>Find!</button>
</div>
<div class="card-body" v-for="items in filteredFounded">
<h5 class="card-title">{{items.companyName}}</h5>
<p class="card-text">{{items.positionName | to-uppercase}}</p>
<p class="card-text">{{items.cityName}}</p>
<p class="card-text">{{items.townName}}</p>
<p class="card-text">{{items.distance}}</p>
Go!
</div>
</div>
</div>
<script src="script.js"></script>
If I understand your issue:
the view updates on each form change since you bound the card-body repeating div directly to the filtering process, so the "Find!" button isn't used
you don't consider the city selection
To fix these, bind a model to the city selector, and declare separate variables for the JSON data and for the selected data:
<select name="" class="city" id="" v-model="city">
and:
data: {
search: "",
sourceJobs: [],
selectedJobs: [],
city: ""
}
Then put you JSON data in sourceJobs on creation:
fetch("job.json").then(function (res) {
this.sourceJobs = res.json();
});
Side note: this architecture will not be viable for large JSON data, maybe you should consider filtering data through a call to your back-end API... but that's not the current question.
Now that your form data is bound to data.search and data.city, and that your pool of jobs is stored in data.sourceJobs, you want to have a method (no more computed) to filter data.sourceJobs and copy the resulting subset in data.selectedJobs:
methods: {
selectJobs: function () {
this.selectedJobs = this.sourceJobs
.filter((job) => {
return job.cityName === this.city && job.positionName.match(this.search);
})
}
}
Finally, call this method when the "Find!" button is clicked:
<button v-on:click="selectJobs">Find!</button>
In case you change you architecture to go for an API call to do the filtering, then you just need to remove that created part and do the API call from within the selectJobs method.
Side, unrelated note: find/found/found (successful result of searching) vs. found/founded/founded (create, build, set a base for something - a city, a company...).
I've got a form with about 10 select elements built from an array in my Vue data.
The array of selectors is empty initially and then an AJAX call populates the array and Vue builds the HTML - I've kept the snippet below simplified just to demonstrate the issue I'm having with v-model
I want to create an object that has all the selected values in it, so I'm trying to use v-model="selected[ selector.name ]" as per the example below.
I want to easily be able to ask for selected.make or selected.fuel
Now this works if I initialize the selected property like this:
selected: { make: 'audi', fuel: 'petrol' }
If I leave it blank, like in the example, {}, then it doesn't get updated.
I don't want to manually hardcode all the properties of selected, I only want to be listing them once in the server side code that gets sent via AJAX
So am I missing something completely obvious, should I be doing this in a different way?
Maybe a method to find the dropdown that matches a field name and returns the value? Just that doesn't seem like a very Vue thing to do.
var app = new Vue({
el: '#example',
data: {
selectors: [
{
name: 'make',
options: ['audi','bmw']
},
{
name: 'fuel',
options: ['petrol','diesel']
}
],
selected: {}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="example">
<template v-for="selector in selectors">
<select v-model="selected[ selector.name ]">
<option v-for="option in selector.options">{{option}}</option>
</select>
</template>
<p>
{{selected.make}}
<br />
{{selected.fuel}}
</p>
</div>
it's probably becuase you're not setting new keys on an object with this.$set
try:
this.$set(this.selected, 'make', 'audi')
Not using this.$set - alias of Vue.set - will mean Vue doesn't set the new key as reactive, and in turn won't be watching for any updates to it, docs: https://v2.vuejs.org/v2/api/#vm-set
var app = new Vue({
el: '#example',
data: {
selectors: [{
name: 'make',
options: ['audi', 'bmw']
}, {
name: 'fuel',
options: ['petrol', 'diesel']
}],
selected: null,
},
created () {
// this would happen following your ajax request - but as an example this should suffice
this.selected = {}
this.selectors
.forEach((selector) => {
this.$set(this.selected, selector.name, '')
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="example">
<div v-if="selected">
<select v-model="selected[selector.name]" v-for="selector in selectors">
<option :value="option" v-for="option in selector.options">
{{option}}
</option>
</select>
<p>make: {{selected.make}}<p>
<p>fuel: {{selected.fuel}}</p>
<pre>{{ selected }}</pre>
</div>
</div>
I'm new to Vue and I would like some help getting a value from an input field:
In my form I have:
<input type="hidden" id="groupId" value="1">
If I was using jQuery I would do:
var group_id = $('#groupId').val();
However, in Vue I don't know how to bind the hidden field:
<div id="app">
<input type="text" v-model="groupId"> //Where do I put the value?
</div>
new Vue({
el: '#app',
data: {
groupId: //What do I put here to get the field's value?
}
How can I achieve this?
Update to the update: See this answer. Previously updated answer was wrong.
Original answer:
In Vue, you don't get things from the view and put things into the view. Vue does that. You do all manipulations in the viewmodel, and make bindings in the view so that Vue knows how to synchronize it. So you'd bind the input to your model data item:
<input type="hidden" id="groupId" v-model="groupId">
and set its value in your viewmodel:
data: {
groupId: 1
}
I had the same question. I'm working with Vue + Laravel.
For me, the solution was simple after searching and not finding a concrete solution in the Vue documentation.
Simply:
document.getElementById('MyId').value;
Details in → https://www.w3schools.com/jsref/prop_text_value.asp
It is not the most efficient solution, but it works for now!
Greetings.
Working sample of getting value from input field in this case it is hidden type:
<input type="hidden" name="test">
<script>
new Vue ({
created () {
const field = document.querySelector("input[name=test]").value
console.log(field)
}
})
</script>
this code helped me
i hope that this work with you
define the input
<div class="root">
<input type="hidden" ref="groupId" value="1">
<button type="button" v-on:click="get_id()">test</button>
</div>
define the method
new Vue({
el: ".root",
data: {
id: null,
}
methods: {
get_id() {
this.id = this.$refs.groupId.value;
}
}
});
// if you want it displayed on your page, use {{ groupId }}
/* you can get the value by using #change.enter=".." #keypress.enter="getInputValue",
or #input="getInputValue" or #click="getInputValue" using button,
or if it is with a form element, #submit.prevent="getInputValue" */
/* #keypress.enter tracks input but only calls the function when the Enter key
is pressed, #input track changes as it's being entered */
// it is important to use event.preventDefault() when using #change or #keypress
<div id="app">
<input type="text" v-model="groupId">
<p> {{ groupId }} </p>
<button #click="getInputValue">Get Input</button>
</div>
new Vue({
el: '#app',
data: {
groupId: //What do I put here to get the field's value?
// for what to put there, you can use an empty string or null
groupId: "",
},
// to get the value from input field
methods: {
getInputValue: function() {
if(this.groupId !== "") {
console.log(this.groupId);
}
},
}
})
look at this I did it in laravel, vuejs, vuetable2 and children's row, and don't use the v-model:
this.$refs['est_'+id_det].localValue
en VUE:
<div class="col-md-3">
<b-form-select class="form-control selectpicker" :ref="'est_'+props.row.id_detalle_oc"
:value="props.row.id_est_ven" v-on:change="save_estado(props.row.id_detalle_oc)">
<option value="0">Sin estado</option>
<option value="1">Pendiente</option>
<option value="2">Impresa</option>
<option value="3">Lista</option>
</b-form-select>
in methods
methods: {
save_estado:function (id_det){
var url= 'ordenes-compra/guardar_est_ven'
var id_estado = this.$refs['est_'+id_det].localValue
axios.post(url,{
id_det: id_det,
id_est_ven: id_estado,
est_ven: est_ve
}).then(function (response) {
var respuesta= response.data;
if(respuesta == "OK"){
swal({
type: 'success',
title: '¡Éxito!',
text: 'Estado modificado',
confirmButtonText: 'Entendido',
})
}
})
.catch(function (error) {
console.log(error);
});
},
I hope it helps, I've been hanging around for a while.
Regards
Hi you can also try the following:
const input = this.$el.firstElementChild;
in case you are using TypeScript, declare input as:
: HTMLInputElement
Then, you can simply get the value if you do:
input.value
Hope it helps!
Ok, this does the job: document.querySelector('#groupId').getAttribute('value');