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);
Related
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.
GOAL:
When a user types character in a text box, make a button appear. When the user clears the text box using the backspace key but holds down that key for a few extra seconds, hide the button instantly.
ISSUE:
If a user types in a single character, and uses the backspace to remove it—by holding down the backspace key a few extra seconds—there is a delay before the button is hidden. This only happens when the user typed only one character and then held down the the backspace key without letting go. If instead the user typed multiple characters, and then held down the backspace key until the textbox was empty, there was no delay in hiding the button.
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
$('#tbox').on('keydown keypress keyup',function(){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
JSFIDDLE:
http://jsfiddle.net/odkut0dh/
A little walkthrough the situation :
Assuming that <input> value is "x" and you type backspace :
- When the keydown event fires the input's value is still "x".
- When the keypress fires, it still "x".
If you don't release the key :
__ keydown fires again, after some delay, depending on os I guess value is now "".
__ keypress fires again, value is still "".
__ When you release the key, keyup fires, value is "".
If you do release the key :
__ keypress fires directly, value is "".
The solution For IE10+ is to use the input event which will fire when the textEditable element's content has changed or, as suggested by #Mayhem, the change event, which won't even listen for key inputs and has a better browser support than input
$('#tbox').on('input change',function(e){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
As i've aleady made comments on this one, did a quick google and came across this post which might make it a little easier.. Detect all changes to a <input type="text"> (immediately) using JQuery
So i put it into a fiddle here for you to test: Slight Modded Version
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').each(function() {
var elem = $(this);
elem.data('oldVal', elem.val());
elem.bind("propertychange change click keyup input paste", function(event){
if (elem.data('oldVal') != elem.val()) {
if (elem.val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
elem.data('oldVal', elem.val());
}
});
});
As i dont have to much time to break this code down into sections... By the looks of it.. You dont need the elem.data... Just the bind event...
... ah seems i decided to shorten the code for you...
http://jsfiddle.net/z2ew3fqz/3/
Using the same HTML...
Shortest version i could make from the example given above
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').bind("propertychange change click keyup input paste", function(event){
if ($(this).val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
});
I've quickly tested this on chrome.. mouse/function keys all seem to affect it correctly... Other browsers i'll leave upto the OP to test.. Let me know if any issues in a particular browser..
IE10 seems to be the min support for this .. IE9 might be able to have a js prototype done.. But how important is this for support in your project? to support IE<10?
The Problem is that $('#tbox').val(); is not empty ('') when backspace is pressed. So You have to delay the value check.
When you press down the key, the first thing what happend is that the keydown event is fired, then after that the key action will be performed on the input field.
$('#tbox').on('keydown keypress keyup',function(){
setTimeout(function () {
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
},0);
});
You can prevent repeating keydown by control it on key up by an global variable:
var allow = true;
$(document).on('keydown', function(e) {
if (e.repeat != undefined) {
allow = !e.repeat;
}
if (!allowed) return;
allowed = false;
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
$(document).keyup(function(e) {
allowed = true;
});
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";
I use VS2010,C# to develop an ASP.NET web app, I'm going to implement a search box like the one used in Stackoverflow (or other sites), initially there is a phrase (for instance "search") in the search text box, when user click in text box, its text is emptied and user can type his phrase, but if he leaves the text box (lost focus) empty, again the phrase "search" is displayed, how can I implement this nice effect?
thanks
This is the textbox watermark plugin which I use:
http://code.google.com/p/jquery-watermark/
I then created the following code which uses the title attribute for the watermark text for all elements with the .textbox_watermark class
var Textbox_Watermark =
{
init: function () {
var textboxWatermarks = $(".textbox_watermark");
for (var i = 0, ii = textboxWatermarks.length; i < ii; i++) {
$(textboxWatermarks[i]).watermark(textboxWatermarks[i].title);
}
}
}
Textbox_Watermark.init();
Then when focus is on the textbox, the watermark is removed.
You will need the jQuery framework for this to work
Here is a little script I use for just this purpose. It does required JQuery though, but if that is an option for you then give it a try. (there is probably a javascript alternative for this too, but I dont know it)
function addInputBlur(selector, text) {
var element = $(selector);
element.blur(function () {
if ($(this).val() == "") {
$(this).val(text);
$(this).addClass("InputBlur");
}
else {
$(this).removeClass("InputBlur");
}
});
element.focus(function () {
if ($(this).val() == text) {
$(this).removeClass("InputBlur");
$(this).val("");
}
});
element.blur();
}
Note: the "selector" param should be a JQuery selector value (i.e. "#MyTextbox")
Also, the "InputBlur" CSS class is just the style I use for the grey/italic font
I have seen the view source for stack overflow and what i notice is that they have a attribute named placeholder
<div id="hsearch">
<form id="search" action="/search" method="get" autocomplete="off">
<div>
<input autocomplete="off" name="q" class="textbox" **placeholder="search"** tabindex="1" type="text" maxlength="140" size="28" value="">
</div>
</form>
</div>
try this it works for mozilla ,, check for others
hope it helps
<input type="text"
onblur="javascript:if(this.value=='') this.value= this.defaultValue;"
onfocus="javascript:if(this.value==this.defaultValue) this.value='';"
id="txtSearch"
value="search"
name="txtSearch" />
You can do this in JavaScript using a function similar to this one:
/*
* applyDefaultValue() - Takes a DOM object and it's string value as paramters, when the element
* is focussed, the 'value' is blanked out, ready for user entry. When the item is blurred, if nothing was typed
* then the original value is restored.
*/
function applyDefaultValue(elem, val) {
elem.value = val;
elem.onfocus = function() {
if (this.value === val) {
this.value = ''; //On focus, make blank
}
}
elem.onblur = function() {
if (this.value === '') {
this.value = val; //If it's not in focus, use declared value
}
}
}
You can then apply this to items like this:
/*
* Onload function to set the default 'email address'/'search' value and blank out the password field
*/
window.onload = function() {
applyDefaultValue(document.getElementById('email'), 'Email Address');
}
Been trying to build jQuery support into a text input where pressing return duplicates the div container into the space right below it. What I can't figure out is how to focus on the input field inside the newly-created div automatically, and, even more frustrating, why that new input field loses the functionality to duplicate. In other words, pressing return only duplicates if you are in the originally-created input field.
$(document).ready(function(){
textboxes = $("input.data-entry");
if ($.browser.mozilla) {
$(textboxes).keypress (checkForAction);
}
else {
$(textboxes).keydown (checkForAction);
}
});
function checkForAction (event) {
if (event.keyCode == 13) {
$(this).clone().val('').appendTo('#form_container');
return false;
}
}
HTML
<div id="form_container">
<input name="firstrow" type="text" class="data-entry">
</div>
use .clone(true) to copy event handlers. see the docs for more info.
$(textboxes).live('keypress', function(checkForAction));