Reputation: 3
I was trying to prevent all characters and symbols if the first character is not #(hash) in jquery or javascript.
This is what I have tried, but keyup
did not work.
<input data-role="tagsinput" type='text' placeholder="Enter search tags..." id="searchtag">
$("#searchtag input").keyup(function () {
if ($(this).val().length >= 1){
if ($(this).val() !== "#"){
$(this).val('');
}
}
});
Upvotes: 0
Views: 37
Reputation: 2191
One option is to prevent every event on key down, therefore the event will not register and you will not need to remove a character that has been added.
NOTE: The if statement can be simplified, written this way for clarity purposes.
Try to run the following snippet:
const input = document.getElementById('searchtag');
input.addEventListener('keydown', function(e) {
if (e.key === '#' && this.value.length === 0) {
// Do nothing
} else if (this.value.length > 0 && this.value[0] === '#') {
// Do nothing
} else {
e.preventDefault();
}
});
<input type="text" id="searchtag">
Upvotes: 2
Reputation: 167202
Your selector is wrong. The input
should come in front or shouldn't come. Use either of it:
$("input#searchtag").keyup(function() {
if ($(this).val().length >= 1) {
if ($(this).val() !== "#") {
$(this).val('');
}
}
});
$("#searchtag").keyup(function() {
if ($(this).val().length >= 1) {
if ($(this).val() !== "#") {
$(this).val('');
}
}
});
When you give a space and input
, it will try to look for the child input
under the element with id #searchtag
.
Upvotes: 0