I would like to be able to dynamically change the types,lables of an input field between text and email,number.
how that possible ,i am new in vue js:
<input type="email">
First you need to declare this in your data:
data () {
return {
inputType: "text",
lableName: "Default",
}
}
Now you use these variables in your html:
<label>{{ lableName }}</label>
<input :type="inputType">
The last part is to define the logic when these values change. However, I don't know when or why you want to change this. If you elaborate I can edit.
Hope this helps already :)
You can use below syntax to make it dynamic
For html:
<input :type="inputType">
In data:
data () {
return {
inputType: 'text'
};
}
Related
My Greeting.
To put in context, my purpose of asking this question is to be able to render a child component inside a form based on the selected option of the <app-selector> Vue component as simple and silly as that.
For the sake of simplicity. I've made a snippet down here to expose what I'm trying to figure out.
Basically, the aim is to get the component name to be rendered by using the computed property cardTypeComponent. However, I want to fathom the way cardTypeComponent is working, since I cannot see why, in one hand, the first return (return this.form) is giving the object (this.form) with the property I want (card_type) but on the other hand the second return (return this.form.card_type ? this.form.card_type + 'Compose' : '') is giving me an empty string, assuming this.form.card_type is undefined when it is clear looking at the first return that, in fact, is not taking it as undefined.
There is way more context, since once the option is selected there is a validation process from the server before setting the value inside this.form object. Moreover, the form interaction is through steps, so once the user select the option he has to click a button to reach the form fields that corresponds to that type card selected, therefore the component is not going to be rendered the very first moment the user selects an option as in the snippet approach. However, it would entangle what I'm asking. Thanks beforehand.
It is better to use the Fiddle link below.
Snippet
var appSelector = Vue.component('app-selector', {
name: 'AppSelector',
template: `<div>
<label for="card_type">Card Type:</label>
<select :name="name" value="" #change="sendSelectedValue">
<option v-for="option in options" :value="option.value">
{{ option.name }}
</option>
</select>
</div>`,
props: {
name: {
required: false,
type: String,
},
options: {
required: false,
type: Array,
}
},
methods: {
sendSelectedValue: function(ev) {
this.$emit('selected', ev.target.value, this.name)
}
}
});
var guessByImageCompose = Vue.component({
name: 'GuessByImageComponse',
template: `<p>Guess By Image Compose Form</p>`
});
var guessByQuoteCompose = Vue.component({
name: 'GuessByQuoteComponse',
template: `<p>Guess By Quote Compose Form</p>`
});
new Vue({
el: '#app',
components: {
appSelector: appSelector,
guessByImageCompose: guessByImageCompose,
guessByQuoteCompose: guessByQuoteCompose,
},
data() {
return {
form: {},
card_types: [
{
name: 'Guess By Quote',
value: 'GuessByQuote'
},
{
name: 'Guess By Image',
value: 'GuessByImage'
}
],
}
},
computed: {
cardTypeComponent: function() {
return this.form; // return { card_type: "GuessByImage" || "GuessByQuote" }
return this.form.card_type ? this.form.card_type + 'Compose' : ''; // return empty string ("") Why?
}
},
methods: {
setCardType: function(selectedValue, field) {
this.form[field] = selectedValue;
console.log(this.form.card_type); // GuessByImage || GuessByQuote
console.log(this.cardTypeComponent); // empty string ("") Why?
}
},
mounted() {
console.log(this.cardTypeComponent); // empty string ("")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form action="#" method="post">
<app-selector
:name="'card_type'"
:options="card_types"
#selected="setCardType"
>
</app-selector>
{{ cardTypeComponent }} <!-- Always empty string !-->
<component v-if="cardTypeComponent !== ''" :is="cardTypeComponent">
</component>
</form>
</div>
https://jsfiddle.net/k7gnouty/2/
You're setting a property on this.form which is not initialized first in data. This means you have run into Vue's change detection caveat. Use Vue.set when setting it:
methods: {
setCardType: function(selectedValue, field) {
Vue.set(this.form, field, selectedValue);
}
}
Alternatively, you could declare the properties first if that works better for you.
Objective: I have a form interface that is being loaded with an object's current data for editing. The user opens this modal with the form that is loaded with the current info so they an either edit it or leave it
Currently working: The form loads with the data from my three objects (details, editSubEvents, instructions) and shows properly without issue
My problem: When I edit the fields and hit submit, I'm only currently dumping the submitted data object to make sure I have what I need. I get the eventID fine becasue it won't change and I get it from the original object. However, I need to store the new title, instruction, and subEvents (as an array) in order to submit them because they're obviously different from the origin ones
How can I properly store the new info from these input fields, including storing the new subEvent title and instructions as an array?
<div class="modal-body">
<div class="form-group row" v-for="detail in details">
<p class="modal-title">Title</p>
<input v-model="detail.title" type="text" class="form-control" id="EventTitle" name="EventTitle">
</div>
<div class="form-group row" v-for="subEvent in editSubEvents">
<p class="modal-title">SubEvent Title</p>
<input v-model="subEvent.title" type="text" class="form-control" id="newSubTitle" name="newSubTitle">
<p class="modal-title">SubEvent Instructions</p>
<textarea v-model="subEvent.instructions" type="text" class="form-control" id="newSubInstructions" name="newSubInstructions"></textarea>
</div>
</div>
data() {
return {
details: [],
instructions:[],
editSubEvents:[],
}
},
methods: {
updateEvent() {
let data = {
EventID: this.details[0].event_id,
title:
origin:
instructions:
subEvents: //needs to be an array
};
console.dir(data);
}
}
All of the properties of your data object can be bound to the UI elements (and most of them are, going by your template example code). The properties of the data object are accessible through the Vue component's this.
new Vue({
el: '#vueApp',
data() {
return {
details: [],
instructions:[],
editSubEvents:[],
}
},
methods: {
updateEvent() {
const data = {
EventID: this.details[0].event_id,
title: this.details[0].title,
origin: this.details[0].origin,
instructions: this.instructions,
subEvents: this.subEvents,
};
console.dir(data);
}
}
}
I am trying to achieve something where in a given input I make the string editable or non editable(readonly) based on the context of the text in vue js.
For example :
I have a text: My Name is $John Doe$
Now my vue js code should iterate the string and the text between $ can be editable.
HTML:
<template>
<textarea cols="10" rows="10" disabled>{{q | makeTextEditableByCondition}}</textarea>
<input type="text" v-model="editText">
</template>
<script>
export default {
data() {
q : "My name is $John Doe$ from NYC,
editText: null,
disabled: true
}
filters:{
makeTextEditableByCondition(text){
let splittedText = text.split("$");
let this.editText = splittedText[1]
splittedText.splice(1,1)
return splittedText.join(" ")
}
</script>
But It's still making the process complicated and I am not achieveing proper output.
Any help will be hightly appreciated
many things are not going well :
q : "My name is $John Doe$ from NYC",
Not ending tag for your filters "}"
... Filters should be pure functions and
should not be dependent on this context. If you need this you should
use a computed property or just a method e.g. https://github.com/vuejs/vue/issues/5998
Here a basic solution with computed :
<div id="app">
<textarea cols="10" rows="10" disabled>{{ qComputed }}</textarea>
<input type="text" v-model="editText">
</div>
new Vue({
el: "#app",
data: {
q: "My name is $John Doe$ from NYC",
editText: null,
disabled: true
},
computed: {
qComputed(){
let splittedText = this.q.split('$')
splittedText[1] = this.editText
return splittedText.join` `
}
}
})
https://jsfiddle.net/jupg4ysz/
I have 2 urls
/register
/register?sponsor=4
The /register route will give me a clean input text in which I can type everything
and the second route will bring a the same input but it has a value of 4 and it's disabled so users cannot modify it.
I managed to get params from router dynamic using vue-router and everything is fine,
but when I visit /register I get the clean input but as soon as I start typing the input will be disabled and I can only type one character.
This what I tried so far,
HTML :
<input :disabled="sponsor ? true : false" v-model="sponsor" id="sponsor" type="number" class="form-control" name="sponsor" value="" required tabindex="14">
Javascript vuejs
<script type="text/javascript">
var router = new VueRouter({
mode: 'history',
routes: []
});
new Vue({
router,
el: '#app',
data () {
return {
cities: [],
city: '',
selectedCountry: '',
sponsor: null
}
},
mounted: function() {
if (this.$route.query.sponsor) {
this.sponsor = this.$route.query.sponsor
console.log(this.sponsor)
}
},
methods: {
onChangeCountry() {
axios.get('http://localhost:8000/api/cities/country/' + this.selectedCountry)
.then(response => this.cities = response.data)
.catch(error => console.log(error))
}
}
});
</script>
disabled is not a Boolean attribute.
The mere presence of the attribute means that the input is disabled.
The only allowed attribute values for disabled are "disabled" and "".
So these three variations are legal to create a disabled input:
<input disabled ... />
or
<input disabled="" ... />
or
<input disabled="disabled" ... />
If you do
<input disabled="false" ... />
that will still disable the input simply because the attribute disabled is on it - on top of being invalid HTML because of an illegal attribute value.
Check it out here:
<input type="text" disabled="false" />
So to solve your problem you need to find a way to not create the attribute on the input in case you don't want to disable it.
Edit: Turns out Vue.js creators have prepared this:
In the case of boolean attributes, where their mere existence implies true, v-bind works a little differently. In this example:
<button v-bind:disabled="isButtonDisabled">Button</button>
If isButtonDisabled has the value of null, undefined, or false, the disabled attribute will not even be included in the rendered element.
https://v2.vuejs.org/v2/guide/syntax.html#Attributes
The problem here is that you are binding the input value to sponsor with v-model="sponsor", so when you star typing, the sponsor get the value and disable the input,
you have to set a flag to know if the value of sponsor comes from the route, and apply the disable logic with that flag. Or directly use the $route.query.sponsor on the :disabled (:disabled="$route.query.sponsor")
<input :disabled="isFromRoute" v-model="sponsor" />
mounted: function() {
if (this.$route.query.sponsor) {
this.sponsor = this.$route.query.sponsor
this.isFromRoute = true //set the flag, make sure to have it in your data section
}
},
Try this one:
<input :disabled="$route.query.sponsor ? true : false" v-model="sponsor" id="sponsor" type="number" class="form-control" name="sponsor" value="" required tabindex="14">
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');