[英]Javascript clear input field on moving focus from one input field to the other
我在輸入數字字段上有以下代碼:
<input class="quantity_container" v-model="length.quantity"
type="number" pattern="[0-9]*" inputmode="numeric"
onfocus="if (this.value == '0') this.value = '';"/>
如果在我切換到其中包含“0”的新輸入字段之前沒有其他輸入字段處於焦點,則清除該字段的代碼有效。 該頁面有許多輸入字段,不幸的是我無法按名稱訪問它們。 我已經檢查並調用了 onfocus,但是當它為“0”並將焦點從一個輸入字段移動到另一個輸入字段時,該字段永遠不會被清除。
只有當我點擊並移除對最后一個輸入字段的關注然后獲得對新輸入字段的關注時,它才會清除。
非常感謝任何幫助。
我將通過創建自定義輸入組件來實現這一點。 例如
Vue.component('quantity-input', {
template: '<input type="number" class="quantity_container" inputmode="numeric" ref="input" :value="value" @input="updateValue($event.target.value)" />',
props: ['value'],
methods: {
updateValue: function(value) {
var formattedValue = value == 0 ? '' : value
if (formattedValue !== value) {
this.$refs.input.value = formattedValue
}
this.$emit('input', formattedValue)
}
}
})
然后你可以簡單地使用
<quantity-input v-model="length.quantity"></quantity-input>
使用 onblur 清除字段,當字段失去焦點時會發生 blur 事件。 在你的情況下,它會像
<input class="quantity_container" v-model="length.quantity"
type="number" pattern="[0-9]*" inputmode="numeric"
onblur="if (this.value == '0') this.value = '';"/>
如果您的輸入字段在頁面加載時有 0 值,您可以將它們清除為
$(document).ready(function() {
$('input[value="0"]').val('');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.