如何在没有 preventDefault() 的情况下禁用 Enter 按钮上的特殊字符?
How to disable special characters on the press of Enter button without preventDefault()?
我有一个搜索字段:
<div class="search-fill">
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." value="@ViewBag.Terms"/>
</div>
以及与之相关的按钮:
<div class="search-submit">
<button id="searchbutton" class="search-button"><i class="fa fa-search" onclick="removeSpecialChar()"></i></button>
当用户按下 Enter 键时,此代码不起作用。我知道我们可以通过 preventDefault() 禁用 Enter,但是有没有其他方法可以做到这一点,因为我希望用户即使在单击 Enter 时也能够搜索?
检查这个
$(function () {
$('[type="search"]').bind('paste input', removeSpecialChars);
})
function removeSpecialChars(e) {
var self = $(this);
setTimeout(function () {
var initVal = self.val(),
outputVal = initVal.replace(/[^A-Z0-9]+/i, '');
if (initVal != outputVal) self.val(outputVal);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." />
document.querySelector("#search").addEventListener("input", ({ target }) => {
const regEx = /([.*+?^$|(){}\[\]])/mg; // example, compose regexp you need
target.value = target.value.replace(regEx, "");
})
我有一个搜索字段:
<div class="search-fill">
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." value="@ViewBag.Terms"/>
</div>
以及与之相关的按钮:
<div class="search-submit">
<button id="searchbutton" class="search-button"><i class="fa fa-search" onclick="removeSpecialChar()"></i></button>
当用户按下 Enter 键时,此代码不起作用。我知道我们可以通过 preventDefault() 禁用 Enter,但是有没有其他方法可以做到这一点,因为我希望用户即使在单击 Enter 时也能够搜索?
检查这个
$(function () {
$('[type="search"]').bind('paste input', removeSpecialChars);
})
function removeSpecialChars(e) {
var self = $(this);
setTimeout(function () {
var initVal = self.val(),
outputVal = initVal.replace(/[^A-Z0-9]+/i, '');
if (initVal != outputVal) self.val(outputVal);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." />
document.querySelector("#search").addEventListener("input", ({ target }) => {
const regEx = /([.*+?^$|(){}\[\]])/mg; // example, compose regexp you need
target.value = target.value.replace(regEx, "");
})