简体   繁体   English

我的 preventDefault 在 jQuery function 中不起作用

[英]My preventDefault not working in jQuery function

I have something like this HTML structure.我有类似 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">

I'm trying to do a validation so that the input only accepts text.我正在尝试进行验证,以便输入只接受文本。 All validation works correctly but prototype preventDefault() is not working.所有验证都正常工作,但原型 preventDefault() 不起作用。 My code:我的代码:

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

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

      }
  })
})

Use input event instead, as it won't work.请改用input事件,因为它不起作用。 And get the last character of event.target.value并获取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