2017-07-25 58 views
-1

我有一個輸入的號碼字段中輸入以下代碼:的Javascript清除輸入領域的其他

<input class="quantity_container" v-model="length.quantity" 
    type="number" pattern="[0-9]*" inputmode="numeric" 
    onfocus="if (this.value == '0') this.value = '';"/> 

的代碼以清除該領域工作,如果沒有其他的輸入字段是焦點在切換到其中具有'0'的新輸入字段之前。頁面有很多輸入字段,不幸的是我不能通過名字訪問它們。我已經檢查過並且焦點已經被調用,但是當它爲'0'並且將焦點從一個輸入字段移動到另一個輸入字段時,字段永遠不會被清除。

只有當我點擊並移除焦點到最後一個輸入字段,然後獲得新焦點時,它纔會清除。

任何幫助非常感謝。

+2

請創建一個[最小,完整,可驗證的示例](https://stackoverflow.com/help/mcve) – Manish

+1

可能可能是因爲你有VueJS模型綁定。您應該在Vue組件/實例中處理驗證,可能通過使用[計算屬性設置器](https://vuejs.org/v2/guide/computed.html#Computed-Setter) – Phil

+2

無法複製。見[這裏](https://jsfiddle.net/Chris_Happy/f6191jnq/)。請提供您的問題演示,例如指向您網站的鏈接,JSfiddle,CodePen或StackOverflow片段。 –

回答

0

使用onblur清除字段,當字段失去焦點時發生模糊事件。在你的情況下,它會像

<input class="quantity_container" v-model="length.quantity" 
    type="number" pattern="[0-9]*" inputmode="numeric" 
    onblur="if (this.value == '0') this.value = '';"/> 

如果你輸入字段具有在頁面加載時0值,你可以通過創建一個custom input component清除它們作爲

$(document).ready(function() { 
$('input[value="0"]').val(''); 
}); 
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>