Input to make "Enter" forbidden - javascript

I have a HTML input in my site and i want to make "ENTER" forbidden in this box.
I mean user should not be able to enter into the box and if the user pasted some text, the enters gets converted to "space character" auto.

you can put this in the onchange of the text input/textarea
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '');|
put this inside your header script tags and you should be good.
<script type="text/javascript" language="javascript">
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
var func = function() {
var text = this.value;
text = text.replace(/\r?\n/g, '');
this.value = text;
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
</script>

<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>

Uses setTimeout and clearTimeout
<input type='text' id='text'>
var timer = null;
$('#text').keydown(function(){
clearTimeout(timer);
timer = setTimeout(doStuff, 1000)
});
function doStuff() {
alert('do stuff');
}
use the doStuff() function to execute code 1 second after user stops typing

Related

How to Prevent/disable copy and paste in Tinymce

I am setting up the tinymce on my system, and want to disable the copy and paste for the user in the tinymce editor, but no where I find the solution. How can I disable the copy paste in tinymce
I have implemented the
Disable pasting text into HTML form
But it is working only in simple text area but not in tinymce textarea
<script>
// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
<body>
<!-- Not Working here-->
<textarea class="tinymce" onpaste="return false;"></textarea>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/init-tinymce.js"></script>
<!-- Working here-->
<textarea onpaste="return false;"></textarea>
</body>
I expect that, it should work in the textarea of tinymce,
Thank you in advance, I will be very gratefull
have you tried to prevent the default
document.addEventListener('paste', function(e){
e.preventDefault();
});
I also read that you can intercept paste in the tinymce.init
paste_preprocess: function(plugin, args) {
console.log(args.content);
args.content = '';
}
Hope that one of those methods works out for you

placeholder javascript fallback for textarea not working

The below is the html code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Please help me point out the mistake. placeholder fallback functionality is not working.I have been debugging it from long time.
Below is the link for fiddle:
check the functionality in ie9 and below as they doesn't support placeholder attribute:
http://jsfiddle.net/DxcYW/
Thanks
Here it is in pure JavaScript:
(function (D, undefined) {
'use strict';
var i, length, placeholder, textareas;
function hidePlaceHolder (placeholder) {
return function (e) {
var target;
target = e.target || e.srcElement;
if (target.value === placeholder) {
target.value = '';
}
};
}
function showPlaceHolder (placeholder) {
return function (e) {
var target;
target = e.currentTarget || e.srcElement;
if (target.value === '') {
target.value = placeholder;
}
};
}
if (! ('placeholder' in D.createElement('textarea'))) {
textareas = D.getElementsByTagName('textarea');
length = textareas.length;
for (i = 0; i < length; i += 1) {
placeholder = textareas[i].getAttribute('placeholder');
textareas[i].value = placeholder;
if (textareas[i].addEventListener) {
textareas[i].addEventListener('focus', hidePlaceHolder(placeholder));
textareas[i].addEventListener('blur', showPlaceHolder(placeholder));
} else {
textareas[i].attachEvent('onfocus', hidePlaceHolder(placeholder));
textareas[i].attachEvent('onblur', showPlaceHolder(placeholder));
}
}
}
}(document));
try putting your JS in
<script> ... </script>
tags. :)
My findings and solution:
Input fields have value attribute but TEXTAREA doesn't have it.
So when we use inputObj.defaultValue="sometext" for input tag it sets the default value as well as current value to sometext, if we dont define the attribute value="something" in the input tag.This works fine from ie9 and above. For below versions if we don't define value="sometext" inputObj.defaultValue="sometext" won't set current value as the default value by itself. For this we can do two things:
we have to manually give value="something which is equal to placeholder text"
we can get the value of placeholder through javascript and set the value from there.
This is not the case with textarea. Textarea doesn't have a attribute value. So when we use textareaObj.defaultValue="sometextarea text" then the default value is set to the given text but not the value itself as we don't have value attribute.value in textarea is nothing but the content between the textarea tags.
Difference between defaultvalue and value:
default value remains the same once it is set.
value is the current value which is being modified by javascript or ourself my typing into the textfield.
For my above issue I found a workaround just by adding one more line to my code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].value = fields[i].getAttribute('placeholder');//setting the value
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Thank you guys for your quick replies and I pity the guy who voted down the question. I feel it is a good question. isn't it ?

Multiple javascript live updating input fields

I would like to have more than one input which can output what the user has put inside the input box on one page and for it to update live. I can currently only get one input to work live.
HTML Code
<input type=text></input><!-- inputs live text -->
<p id="headingone"></p><!-- outputs live text -->
Javascript Code
function reverse(s) {
return s.split('').reverse().join('')
}
function set(el, text) {
while (el.firstChild) el.removeChild(el.firstChild);
el.appendChild(document.createTextNode(text))
}
function setupUpdater() {
var input = document.getElementsByTagName('input')[0]
, orig = document.getElementById('headingone')
, oldText = input.value
, timeout = null;
function handleChange() {
var newText = input.value;
if (newText == oldText) return;
else oldText = newText;
set(orig, newText);
}
function eventHandler() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(handleChange, 50);
}
input.onkeydown = input.onkeyup = input.onclick = eventHandler;
}
setupUpdater();
document.getElementsByTagName('input')[0].focus();

How to send Keyboard events (e.g. Backspace, Delete) in Safari from Javascript

I'm implementing an on-screen Keyboard for a Javascript application. The text should appear in a textarea-Element. I've no problem creating text-events but feel unable to create non-text events such as the Backspace. Here is some sample code:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function log(text) {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML += "<br/>" + text;
}
}
function logEvent(e) {
log("Type: " + e.type + ", which: " + e.which + ", keyCode: " + e.keyCode + ", charCode: " + e.charCode + ", keyIdentifier: " + e.keyIdentifier + ", data: " + e.data);
}
function logClear() {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML = "";
}
}
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("KeyboardEvent");
ke1.initKeyboardEvent("keydown", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// how to set "keyCode" and "which"?
// 1. ke1.keyCode = 8; will be ignored due to "writable: false"
// 2. delete ke1.keyCode will be ignored too
// and Object.defineProperty(KeyboardEvent.prototype, "keyCode", ... whatever ...);
// will result in Exception due to "configurable: false"
// 3. generating a more general Event (e.g. "var e = document.createEvent("Events");")
// and setting all necessary props (e.g. "e.initEvent("keydown", true, true);e.keyCode=8;e.which=8;")
// will work, but the textarea will ignore the Event
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("KeyboardEvent");
ke2.initKeyboardEvent("keyup", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// same question as above
textarea.dispatchEvent(ke2);
}
function init() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", logEvent, false);
textarea.addEventListener("keypress", logEvent, false);
textarea.addEventListener("keyup", logEvent, false);
textarea.addEventListener ("textInput", logEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
<button onclick="logClear()">clear log</button><br/>
<div id="log"></div>
</body>
</html>
The interesting function here is sendBackEvent(). I tried hard to get exactly the same event like pressing the Backspace-Button on the physical Keyboard but didn't succeed.
I know there is a Webkit-Bug but hoped there could be some other way to get this working. Has anyone had the same problem? Could it be solved? How? The proposed solution here (calling new KeyboardEvent(...) ) doesn't work because directly calling the KeyboardEvent constructor results in following exception:
Exception: TypeError: '[object KeyboardEventConstructor]' is not a constructor (evaluating 'new KeyboardEvent(...)')
I have no more ideas.
Since there seem to no way out, i found myself constrained to install my own backspace event handler. The working code (without logging now) is here:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("Events");
ke1.initEvent("keydown", true, true);
ke1.keyCode = ke1.which = 8; // Backspace
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("Events");
ke2.initEvent("keyup", true, true);
ke2.keyCode = ke2.which = 8; // Backspace
textarea.dispatchEvent(ke2);
}
function handleBackEvent(e) {
if(e.keyCode != 8) {
return;
}
if (textarea.value.length == 0) {
return;
}
var text = textarea.value;
var selectionStart = textarea.selectionStart;
var selectionEnd = textarea.selectionEnd;
if (selectionStart < selectionEnd) {
var text1 = (selectionStart > 0 ? text.slice(0, selectionStart) : "");
var text2 = (selectionEnd < text.length ? text.slice(selectionEnd) : "");
textarea.value = text1 + text2;
}
else if (selectionStart > 0) {
var text1 = (selectionStart - 1 > 0 ? text.slice(0, selectionStart - 1) : "");
var text2 = (selectionStart < text.length ? text.slice(selectionStart) : "");
textarea.value = text1 + text2;
selectionStart--;
}
textarea.selectionStart = textarea.selectionEnd = selectionStart;
e.preventDefault();
e.stopPropagation();
return false;
};
var textarea;
function init() {
textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", handleBackEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
</body>
</html>
Just in case someone else run into same trouble.

jQuery + Get and Compare Element VALUE and ALT

I am trying to modify following script to do this check:
Check if input VALUE and ALT are the same.
If yes: empty VALUE
If no: keep VALUE
This is the script I am working on: (the part that i commented out, is where i tryed to figure out how to make the changes myself).
<script language="Javascript" type="text/javascript">
//<![CDATA[
jQuery.fn.placeholder = function(){
return this.each(function(){
var element = $(this)
var insertedNow =element.after("<span class='placeholder-spanbox'>"+ element.attr('alt')+ "</span>").attr("alt","").next('.placeholder-spanbox');
var leftOffset = (element.innerWidth() - element.width())/2+parseInt(element.css("border-left-width"));
var topOffset = ((element.innerHeight() - element.height())/2)+parseInt(element.css("border-top-width"));
var inputWidth = element.width();
var inputHeight = element.height();
var placeholderPos = inputHeight + topOffset + leftOffset;
insertedNow.css("padding-left",leftOffset+"px").css("padding-top",topOffset+"px").css("opacity",0.5).css("display","block").css("margin-top",-placeholderPos).css("cursor","text");
var objCSS = {'-webkit-transition':'opacity 100ms ease-in','-moz-transition':'opacity 100ms ease-in','-o-transition':'opacity 100ms ease-in','-ms-transition':'opacity 100ms ease-in','transition':'opacity 100ms ease-in','font-size':element.css('font-size'),'font-family':element.css('font-family'),'color':'#000000','font-weight':element.css('font-weight'),'width':element.css('width'),'float':element.css('float')};
insertedNow.css(objCSS);
//insertedNow.offset(element.offset());
element.bind("focus",updateSpanStatusFocus);
element.bind("keydown",updateSpanStatusKeyDown);
element.bind("keyup",updateSpanStatusKeyUp);
element.bind("blur",updateSpanStatusBlur);
insertedNow.bind("click",clickSpanBox);
var inputVal = element.attr("value");
var inputAlt = element.attr("alt");
//$(this).attr("value",+inputVal);
// if(inputVal == inputAlt){
// $(this).attr("value","123");
// }
if(element.val()!==""){
insertedNow.css({'opacity':0});
}
});
function clickSpanBox(event){
event.preventDefault();
var inputBox = $(this).prev();
inputBox.focus();
}
function updateSpanStatusFocus(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyUp(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyDown(event){
var $this = $(this);
if($this.val()=="" && (event.keyCode>54 || event.keyCode == 32)){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0");
}
}
function updateSpanStatusBlur(){
var $this= $(this);
$this.val(Trim($this.val()+''));
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.5");
spanBox.css("color","#000000");
}
}
}
$(document).ready(function(){
$('.spanOverlay').placeholder();
});
//]]>
</script>
And here the html markup example:
<input type='text' name="userName" class='contactInput spanOverlay' alt='* Name' value='test'></input>
Thanks for your help!!
Is this what you want?
if (element.val() == element.attr('alt')) {
element.val("");
}
there's something called .defaultValue in javascript u could use this to compare against current value
here's an example on how its done
http://www.miuaiga.com/index.cfm/2009/8/31/jQuery-form-input-defaultValue

Categories