我需要限制/禁用最终用户在输入字段或文本框字段中输入空格。目前,我正在使用此代码,但无法正常工作。
function keyPress(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
return;
}
}
答案 0 :(得分:1)
尝试按键而不是按键。
function keyDown(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
e.preventDefault();
}
}
<input type="text" onkeydown="keyDown(event)" />
修改
如果要防止插入包含空格的粘贴文本,可以使用以下代码:
function keyDown(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
e.preventDefault();
}
}
function checkWhitespace(event)
{
var data = event.clipboardData.getData("text/plain");
var isNullOrContainsWhitespace = (!data || data.length === 0 || /\s/g.test(data));
if(isNullOrContainsWhitespace)
{
event.preventDefault();
}
}
<input type="text" onkeydown="keyDown(event)" onpaste="checkWhitespace(event)" />
答案 1 :(得分:0)
尝试一下
LEA
答案 2 :(得分:0)
在文本框的keypress事件上尝试此代码
<input type="text" onkeypress="keyDown()"/>
<script>
function keyDown(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
e.preventDefault();
}
}
</script>
答案 3 :(得分:0)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function forum()
{
return $this->belongsTo('App\Models\Forum');
}
}
<!-- Javascript -->
<!-- prevent space in text box by -->
function RestrictSpace() {
if (event.keyCode == 32) {
return false;
}
}
<!--preventing copy and pasting to text box-->
function preventcopypaste(event) {
var data = event.clipboardData.getData("text/plain");
var isNullOrContainsWhitespace = (!data || data.length === 0 || /\s/g.test(data));
if (isNullOrContainsWhitespace) {
event.preventDefault();
}
}