why doesn't change the value of my input? - vue.js

I have an input where passing the value of my star-rating module. When i use my function with v-model, the value of my input change (for example '4'), but the value it's not read with my function #input.
My code in template:
<div v-if="question.element_type=='notation'">
<star-rating
inactive-color="#4c514c"
v-bind:star-size="30"
v-model="selectedNote"
#rating-selected ="next"
:rounded-corners="true"
:show-rating="false">
</star-rating>
<textarea
v-model="selectedNote"
class="myTextarea"
maxlength="1"
:name="'q'+question.id"
#input="next">
</textarea>
</div>
my two functions :
setRating: function(rating) {
this.selectedNote = rating
},
next(evt){
this.selectedNote = evt.target.value
if(evt.target.value.length)
this.affichageSuivant = true
else
this.affichageSuivant = false
},
and my state of seletedNote
selectedNote: 0,

Related

Does Vuejs have the ability to combine data fields into one?

I currently have a datetime field in my vue application. I want to split it up, but that would mean having to split it up in my database as well, which I am not interested in. I still want to keep the datetime column in my database table.
So my idea was to make it like 3 seperate fields: datetime, date and time. When a user has entered a date and time, these can be merged into the datetime field.
In Python you would do something like: datetime.datetime.combine( date, time )
Is there are similar method in Vue, or is there a better way of getting around this?
<b-form-row>
<b-col lg="6">
<b-form-group :label="$t('check in time')">
<time-picker v-model="guest.checkInDateTime" />
</b-form-group>
</b-col>
</b-form-row>
<b-form-row>
<b-col lg="6">
<b-form-group :label="$t('check in date')">
<date-picker v-model="guest.checkInDateTime" />
</b-form-group>
</b-col>
</b-form-row>
<b-form-row>
<b-col lg="6">
<b-form-group :label="$t('check in time and date')">
<date-time-picker v-model="guest.checkInDateTime"
:format="format"
:show-second="false"
type="datetime"/>
</b-form-group>
</b-col>
</b-form-row>
Working with dates in Javascript can be nuanced. In Javascript, assuming you have both a date value and a time value, you can easily combine these into a date string used by an html date picker like this:
const date = '2022-08-10' // string returned from date input
const time = '15:00:00' // string returned form time input
const checkInDateTime = date + 'T' + time // ISO String
If you're starting with a Date and you want to break it into a date value and a time value, it's almost easier using string manipulations than working with the Date obj, unless you're using a helper library like dayjs.
Examples:
// Assuming we have a date in ISO String format YYYY-MM-DDTHH:mm:ss
const dateFromString = dateValueFromDB.split('T')[0]
const timeFromString = dateValueFromDB.split('T')[1]
// using Date obj
const d = new Date(dateValueFromDB);
const dateFromObj = `${d.getFullYear()}-${('' + (d.getMonth() + 1)).padStart(2, '0')}-${('' + date.getDate()).padStart(2, '0')}`
const timeFromObj = `${d.getHours()}:${('' + d.getMinutes()).padStart(2,'0')}:${('' + d.getSeconds()).padStart(2,'0')}`
// using dayjs library
const dateFromDayjs = dayjs(dateValueFromDB).format('YYYY-MM-DD')
const timeFromDayjs = dayjs(dateValueFromDB).format('HH:mm:ss')
Now to answer your original question. Once we know how we're getting the correct values, in Vue.js, we can easily get and set these date values using a computed property and a custom setter.
<script>
export default {
data() {
return {
guest: {
checkInDateTime: '2022-09-10 15:00:00' // timestamp returned from database
}
}
},
computed: {
time: {
get() {
return dayjs( this.guest.checkInDateTime ).format('HH:mm:ss')
},
set(val) {
this.guest.checkInDateTime = this.date + 'T' + val
}
},
date: {
get() {
return dayjs(this.guest.checkInDateTime).format('YYYY-MM-DD')
},
set(val) {
this.guest.checkInDateTime = val + 'T' + this.time
}
}
}
}
</script>
Here's the html:
<template>
<div class="datetime-pickers">
<p>date: <input type="date" v-model="date" /></p>
<p>time: <input type="time" v-model="time" /></p>
<p>checkInDateTime: <input type="datetime-local" v-model="guest.checkInDateTime" /></p>
</div>
</template>
When any of the three values are set, the other two are updated accordingly. Here's a CodePen showing this in action:
https://codepen.io/ryanhightower/pen/ExLPobY?editors=1010

Vue 3 "v-model" with checkboxes but the data is "1" or "0" not "true" or "false"

Because of some reason on the backend, they use 0 or 1 and not false or true for booleans.
So, when I try to use the boolean data from API, TS complains:
// settings.crawl_on outputs 0 or 1
<input
v-model=“settings.crawl_on”
type="checkbox"
/>
I tried adding the below code it doesn't work either:
true-value="1"
false-value="0"
TS says:
(property) InputHTMLAttributes.checked?: any[] | Set | Booleanish
Type 'number' is not assignable to type 'any[] | Set |
Booleanish'.ts(2322)runtime-dom.d.ts(629, 3): The expected type comes from property 'checked' which is declared here on type
'ElementAttrs'
Is there a way to override this or what is the correct use?
Upgraded from Vue 2 to Vue 3, got same issue. This didn't work:
true-value="1"
false-value="0"
But this works:
:true-value="1"
:false-value="0"
For input type="checkbox", 0 will be same as false and 1 will be same as true.
Hence, settings.crawl_on = 1 will be same as settings.crawl_on = true.
I checked same with TypeScript as well as JavaScript and it's working fine in both the languages.
Demo :
new Vue({
el: '#app',
data: {
settings: {
crawl_on: 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input
v-model="settings.crawl_on"
type="checkbox"
/>
</div>
Because static html attributes values are 'String' type. And you are expecting 'Integers'.
So, when you use "v-bind:" making attributes dynamic values, you are sending 'Integers'
true-value="1" <-- string
true-value="1" <-- integer
:true-value="'1'" <-- string

Angular5 data prepopulation one way binding not happening

I am using a parent component travelerInput that creates travelerListForm using model in my component and iterate it extracting travelerForm which is then passed to the nested child components using #Input:
for (let i = 1; i <= numberOfTravelers; i++) {
const tId = `${ptc}_0${i}`;
const Id = `${TravelerInput.pIndex++}`;
const traveler = new Traveler({passengerTypeCode: ptc, id: Id, tid: tId, names: [new Identity({
firstName: "",
middleName: "",
lastName: "",
title: "",
nameType: "native",
isDisplayed: false
})],
dateOfBirth: undefined ,
gender: "unknown",
accompanyingTravelerId: "",
accompanyingTravelerTid: ""
});
travelerList.push(traveler);
}
HTML
<div class="alpi-section col-xs-12 col-sm-12 col-md-12 col-lg-12"
*ngFor="let travelerForm of travelerListForm.controls; let tIndex = index;">
<o3r-simple-traveler-input
[config]="config.simpleTravelerInput"
[travelerForm]="travelerForm"
[index]="tIndex">
</o3r-simple-traveler-input>
Now we have a drop down in parent component with a list of travelers. The selected passenger in the drop down will have its information prepopulated in the form fields which are nested child components. I am using travelerForm which is iterated over travelerListForm in child components as #Input. On change of drop down I am binding the value of the passenger information to the corresponding index of travelerListForm which is also getting updated but on UI there is no update.
pickSelectedADTPassenger(adult:any, index: number){
this.selectedADTId= this.ADTTravelerId[adult];
this.travelerListForm.controls[index].value.names[0].firstName = this.selectedADTId.IDENTITY_INFORMATION.FIRST_NAME; //ASSISGNMENT
}
Have also tried using ngModel in the child component input field where I want the value to be prepopulated but it did not work:
<input type="text"
[(ngModel)]="travelerForm.controls.firstName.value"
class="form-control"
placeholder="FIRST NAME"
maxlength="52"
formControlName="firstName">
</div>
Please suggest.

Check if value exists in vuejs

I have data : 1,2,3,4,4,5 & my code like this:
<div id="looping" v-for="display in editlistAssesments">
{{display.test_id}}
</div>
My code if in php such as like this
$temp_id = array();
foreach($data as $data){
if(in_array($data ->test_id,$temp_id)){
echo" 1: no";
echo" 2: no";
echo" 3: no";
echo" 4: yes"; //because he have same value
echo" 5: no";
$temp_id[] = $data ->test_id;
}
}
how I can do that in loop vueJs..??
From my point of view, the best way is:
<div id="looping"
v-for="display in editlistAssesments">
<span v-if="typeof display.test_id !== 'undefined'">
{{display.test_id}}
</span>
</div>
Because if you use v-if="display.test_id" and the test_id value is 0 (boolean comparation) you will never see the display.text_id.
You can use also this another condition to check if is null or undefined: display.test_id != null (loose equality operator)
As far as I understand, you want to check if value is in array and then render it accordingly?
If so, you need a Vue custom filter. Something like this will do the trick:
var vm = new Vue({
el: 'body',
data: {
editlistAssesments: [1,2,3,4,4,5]
},
filters: {
ifInArray: function (value) {
return this.editlistAssesments.indexOf(value) > -1 ? 'Yes' : 'No';
}
},
});
And then use it like this:
<div id="looping" v-for="display in editlistAssesments">
<span v-text="display.test_id | ifInArray"></span>
<!-- bind Vue value to html element is better practice -->
</div>
Check docs for more information:
http://vuejs.org/guide/custom-filter.html

Ember.js input fields

Is it possible to use standard HTML5 input fields in an Ember.js view, or are you forced to use the limited selection of built in fields like Ember.TextField, Ember.CheckBox, Ember.TextArea, and Ember.select? I can't seem to figure out how to bind the input values to the views without using the built in views like:
Input: {{view Ember.TextField valueBinding="objectValue" }}
Specifically, I'm in need of a numeric field. Any suggestions?
EDIT: This is now out of date you can achieve everything above with the following:
{{input value=objectValue type="number" min="2"}}
Outdated answer
You can just specify the type for a TextField
Input: {{view Ember.TextField valueBinding="objectValue" type="number"}}
If you want to access the extra attributes of a number field, you can just subclass Ember.TextField.
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step']
})
Input: {{view App.NumberField valueBinding="objectValue" min="1"}}
#Bradley Priest's answer above is correct, adding type=number does work. I found out however that you need to add some attributes to the Ember.TextField object if you need decimal numbers input or want to specify min/max input values. I just extended Ember.TextField to add some attributes to the field:
//Add a number field
App.NumberField = Ember.TextField.extend({
attributeBindings: ['name', 'min', 'max', 'step']
});
In the template:
{{view App.NumberField type="number" valueBinding="view.myValue" min="0.0" max="1.0" step="0.01" }}
et voile!
Here is my well typed take on it :
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numericValue: function (key, v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value')
});
I use it that way:
{{view App.NumberField type="number" numericValueBinding="prop" min="0.0" max="1.0" step="0.01" }}
The other systems where propagating strings into number typed fields.
You may also wish to prevent people from typing any old letters in there:
App.NumberField = App.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numbericValue : function (key,v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value'),
didInsertElement: function() {
this.$().keypress(function(key) {
if((key.charCode!=46)&&(key.charCode!=45)&&(key.charCode < 48 || key.charCode > 57)) return false;
})
}
})
Credit where its due: I extended nraynaud's answer
This is how I would do this now (currently Ember 1.6-beta5) using components (using the ideas from #nraynaud & #nont):
App.NumberFieldComponent = Ember.TextField.extend
tagName: "input"
type: "number"
numericValue: ((key, value) ->
if arguments.length is 1
parseFloat #get "value"
else
#set "value", (if value isnt undefined then "#{value}" else "")
).property "value"
didInsertElement: ->
#$().keypress (key) ->
false if (key.charCode isnt 46) and (key.charCode isnt 45) and (key.charCode < 48 or key.charCode > 57)
Then, to include it in a template:
number-field numericValue=someProperty