簡體   English   中英

我的 preventDefault 在 jQuery function 中不起作用

[英]My preventDefault not working in jQuery function

我有類似 HTML 結構的東西。

<input type="text" id="client-first-name" autocomplete="given-name" class="input-small error" data-bind="value: firstName, validate: 'alphaNumericPunctuation', valueUpdate:'afterkeydown', required: true, disable: loading">

我正在嘗試進行驗證,以便輸入只接受文本。 所有驗證都正常工作,但原型 preventDefault() 不起作用。 我的代碼:

$(document).ready(function () {
  $("#client-first-name").keyup(function(event){

    if(!/^[A-Z]+$/i.test(event.key)){
        event.preventDefault()

      }
  })
})

請改用input事件,因為它不起作用。 並獲取event.target.value的最后一個字符

$(document).ready(function () {
  $("#client-first-name").on('input', function(event){

    var newValue = event.target.value

    if(!/^[A-Z]+$/i.test(newValue[newValue.length - 1])){
      event.preventDefault()
    }
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM