0

I have a search field:

 <div class="search-fill">
 <input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." value="@ViewBag.Terms"/>
 </div>

and a button related to it:

<div class="search-submit">
<button id="searchbutton" class="search-button"><i class="fa fa-search" onclick="removeSpecialChar()"></i></button>

This code does not help when the user presses the Enter key. I know we can disable the Enter through preventDefault(), but is there any other way to do this, as I want the user to be able to search even on clicking Enter?

  • Wouldn't it be better to just clean the search string before you use it rather than prevent the user from using specific characters? That might be a more practical approach. – fixatd Dec 18 '18 at 10:16
  • 1
    Possible duplicate of [How to prevent user from entering special characters in text box when length is 0?](https://stackoverflow.com/questions/18608954/how-to-prevent-user-from-entering-special-characters-in-text-box-when-length-is) – Prashant Pimpale Dec 18 '18 at 10:18

2 Answers2

0

Check this

$(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..." />
Ahmed Ghoniem
  • 661
  • 1
  • 8
  • 15
0
document.querySelector("#search").addEventListener("input", ({ target }) => {
    const regEx = /([.*+?^$|(){}\[\]])/mg; // example, compose regexp you need
    target.value = target.value.replace(regEx, "");
})
Eugen Govorun
  • 3,006
  • 1
  • 11
  • 12