How to prevent user pasting text in a textbox? - javascript

I have this JS function that prevents user from typing characters
<script type="text/javascript">
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if(!regex.test(key)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
<span>Radio Receive:</span>
<input name="ReceiveNo" type="text" class="txtbox" onkeypress='validate(event)' maxlength="11" value="${cpCon.receiveNo}" required tabindex="34" />
But I noticed that when the user tried to paste a word from this textbox, the text can be entered. How can I prevent this without disabling the paste?

Very Easy Solution:
<input name="ReceiveNo" type="text" class="txtbox" onkeypress='validate(event)' maxlength="11" value="${cpCon.receiveNo}" required tabindex="34" onCopy="return false" onDrag="return false" onDrop="return false" onPaste="return false" autocomplete=off />
This worked for me very well. No one can paste now into your textbox using right button paste option of mouse or pressing ctrl+v from the keyboard.

// To Disable the paste functionality
$(document).ready(function(){
$('#txtInput').bind("paste",function(e) {
e.preventDefault();
});
});
// Below One might be helpful for your functionality.
$(document).ready(function(){
$('#txtInput').bind("paste",function(e) {
validate(e);
});
});
or
OnTabOut() or onblur() you can validate the entered / pasted text instead of handling the paste functionality.

I tried this in my Angular project and it worked fine without jQuery.
<input type='text' ng-paste='preventPaste($event)'>
And in script part:
$scope.preventPaste = function(e){
e.preventDefault();
return false;
};
In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instead of '$event'.

If you simply need non editable kendoComboBox(), you could use kendoDropDownList() instead.
In my case i needed it to be enabled/disabled depending on user privileges,
so here's the solution i came up with (this prevents key inputs and pasting values) :
if (user.hasRight()) {
var myinput = $("#myinput").data("kendoComboBox");
myinput.input.on("keydown", function (e) { e.preventDefault(); });
myinput.input.bind("paste", function (e) { e.preventDefault(); });
}
You can test it here

VanillaJS solution
function pasteNotAllowFunc(xid){
let myInput = document.getElementById(xid);
myInput.onpaste = (e) => e.preventDefault();
}
pasteNotAllowFunc('pasteInput')
Paste
<input id="pasteInput" value="paste not allow"/>
<hr/>
Textarea
<textarea id="test" value="Copy me and try to paste"></textarea>

jQuery:
$(this).click(function () {
$(".txtbox").attr("disabled", "disabled");
});
or css:
.txtbox{
display: none;
visibility: hidden;
}
or html attribute:
set disabled="disabled";

Related

Keep focus on input type text/search on keypress

I've written a simple input of type text, but when I press enter while my cursor is inside the textbox, it looses the focus. How can I ignore enter key to stop losing focus from the text box? I tried doing something like this:
<input type="text" (keyup)="keepFocus($event)" />
and keepFocus() is a method:
keepFocus(e) {
e.target.select();
}
But this method is called everytime I press a key, which is not very efficient. Is there a better solution to handle this behavior?
You capture just the enter key, and prevent default when it's pressed
document.getElementById('myInput').addEventListener('keypress', function(event) {
if (event.which === 13) event.preventDefault();
});
<input type="text" id="myInput" />
Another way to do this is by getting the keyCode (that e parameter use).
I mean, use this:
http://www.javascripter.net/faq/keycodes.htm
And this:
https://www.w3schools.com/jsreF/event_preventdefault.asp
Something like this would be fine:
function keepFocus(e) {
if(e.keyCode == 13)
e.preventDefault();
}
<input type="text" keyup="keepFocus" />
This will prevent that you lost the focus when enter key is pressed!
There are two ways to do the job.
First, reput the focus to the input when the user click "Enter":
<input type="text" onkeyup="keepFocus(event);" id="teste" />
function keepFocus(e) {
if (e.key=="Enter") {
var teste = document.getElementById ("teste");
teste.focus ();
}
}
Second, prevent the default behavior of the text field:
function keepFocus(e) {
if (e.key=="Enter") {
e.preventDefault ();
}
}
I think the second way is better because you do not have to add an id to your input.

jQuery keypress enter not working

I tried to use keypress to get an text from to update a text in . My html looks like this:
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag"></input>
</form>
</div>
My jQuery looks like this:
$(document).ready(function () {
$("input").keypress(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
}
}
);
})
My console log doesn't log on first keypress, how can I help it? Also my "hello" never log. Any ideas why this is happening?
Thanks!
Use keyup event to capture first keyboard char.
$(document).ready(function () {
$("input").keyup(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
alert('hello');
}
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>
Note: Hitting Enter key will submit the form and it will redirect the page. You might not see the console message for "hello"
The keypress function fires right as a key is pressed. You want to use keyup as that will fire when the key is released.
You need to use keyup as keypress will trigger value as soon as a key is pressed which is separate from releasing a key.
There are few changes that can be done. input is a self closing tag. Also it is better to use $(this) inside the function as it will get the value only from the input from where the event is triggered.
There may be a catch here. On pressing enter/return key you may see the form is getting submitted
$(document).ready(function() {
$("input").keyup(function(e) {
var currentInput = $(this).val();
console.log(currentInput);
if (e.keyCode == 13) {
console.log('hello');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>

Make google image search initiate on press of 'enter'

http://protected-river-1861.herokuapp.com/ Link to my site
So, I need to let the search of Google Images initiate on the press of the 'enter' key. Currently, it only works on the click of the button.
HTML:
<p>Enter the keyword to search for images</p>
<input id="search-term" type="text">
<button id="go-search">Go!</button>
<div id="search-results"></div>
<div style="width: 150px; margin:0 auto;">
application.js:
$(document).on('click', '#go-search', function() {
findImagesOnGoogle({keywords: $('#search-term').val(), container: '#search-results'})
});
$(document).on('click', '#search-results img', function() {
var url = $(this).data('url');
$("#workspace img").remove();
var img = $("").attr('src', url);
$("#workspace").append(img);
});
The CSS, JS and HTML are all on separate tabs in Sublime Text.
I think this Code can help you. I am not providing you entire solution but making way for you to learn to do code by yourself.
<input type="text" placeholder="Enter Search Term & Press Enter.." onkeydown="javascript:return checkEnterPressed(event);" />
<script type="text/javascript">
function checkEnterPressed(thisEvent) {
if (thisEvent.keyCode == 13) { // 13 : Enter Key
alert('enter Pressed');
// Do WHatever you want to do HERE.
return true;
}
}
</script>
Based on the code you provided you can try something like
$('#search-term').on("keypress", function(e) {
if (e.keyCode == 13) {
findImagesOnGoogle({keywords: $('#search-term').val(), container: '#search-results'})
}
});
});
and put put this after your last line of code.
An example (not with a search, but with a popup is here) jsFiddle

How to go to next textbox when enter is pressed?

Hi guys I'm learning Javascript and I would like to ask you guys how can I go to the next textbox after inputing text when I press the enter button in the keyboard. thank you
You can use .keyup() to keep track of when user finish key in a character and e.keyCode to get which key was pressed, if it's 13(means enter) then use .focus() to focus the next textbox element:
$('input[type="textbox"]').keyup(function(e) {
if(e.keyCode == 13) {
$(this).next().focus();
}
});
Fiddle Demo
Try this code :
$('#inputform').on('keydown', 'input', function (event) {
if (event.which == 13) {
event.preventDefault();
var $this = $(event.target);
var index = parseFloat($this.attr('data-index'));
$('[data-index="' + (index + 1).toString() + '"]').focus();
}
});
Help Link
I've developed a plugin to include enter event.
(function ($) {
$.fn.enter = function (func) {
this.bind('keypress', function (e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
You can call it like this:
$('#input1').enter(function(){ $(this).next().focus(); });
You can go to the next field in many ways, as demonstrated by all the answers here, but don't forget to assign the order of what is actually NEXT as well. You can go from field to field with the TAB button, and the layout of your site may not always go in the order you'd expect or want. The solution to this is to add tabindex="" to your fields as such:
<input type="text" tabindex="1" />
<input type="password" tabindex="2" />
<input type="submit" value="Log In" tabindex="3" />

Detect paste in input box

I have a input box, and I would like to use vbscript or javascript (no jquery) to capture the paste event.
Use the onpaste event to capture the event and do what you need in Javascript. E.g. to disable the paste in an input text field:
<input type="text" onpaste="return false;" />
Javascript supports onpaste:
http://www.quirksmode.org/dom/events/cutcopypaste.html
Just for future readers finding this as I did.
You will still be able to drop text into an input with the onpaste="return false;" attribute. If you want to avoid this, you can do something like this:
var input_element = document.getElementById("Element");
input_element.addEventListener("drop", function (event) {
var types = event.dataTransfer.types;
if (types.length > 2 || types.indexOf("text/plain") === -1)
event.preventDefault();
else {
setTimeout(function () { input_element.value = ""; }, 10);
}
}, false);

Categories

Resources