如何防止用户删除文本输入中的前三个字符? [英] How to prevent a user from removing the first three characters in a text input?

查看:93
本文介绍了如何防止用户删除文本输入中的前三个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本输入,当页面加载时有三个动态生成的字符;我想要的是当用户输入数据时,用户应该无法从输入中删除前三个字符。

I have a text input, which has three dynamically-generated characters On when page-load; what I want is that when a user enters data in that fieLd the user should be unable to remove that first three characters from the input.

文本输入可以包含10个字符我们生成了3个,用户输入了7个。

The text input can contain 10 characters in total, three which we generate and 7 entered by the user.

目前,如果用户按退格键,他可以删除所有字符,但我不想允许它们删除前三个字符。

Currently if the user presses backspace he can delete all characters, but I don't want to allow them to delete the first three characters.

在页面加载时,脚本在Lab文本输入中设置三个字符:

On page-load the script sets three characters in the Lab text input:

<input id="Lab" maxlength="10" name="LabWareId" type="text" value="" class="valid">

$('#Lab').keyup(function () {
  if ($(this).val().length == $(this).attr('maxlength'))
    $('#DateReceived').focus();
});


推荐答案

选项1 :放输入外的3个字符前缀。从用户体验的角度来看,这是最好的。

Option 1 : Put the 3 character prefix outside of the input. This is the best from a user experience perspective.

<p>abc <input id="Lab" maxlength="10" name="LabWareId" type="text" class="valid"></p>

选项2 :检查退格键按压并相应地阻止删除。

Option 2 : Check for backspace keypress and prevent the delete accordingly.

$(document).on('keydown', function (e) {
  if (e.keyCode == 8 && $('#Lab').is(":focus") && $('#Lab').val().length < 4) {
      e.preventDefault();
  }
});

这篇关于如何防止用户删除文本输入中的前三个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆