I have following sample code at https://js.do/sun21170/254818
My goal is to prevent editing of text inside the textbox without using the readOnly or disabled attribute. In above demo code, I am canceling the keyup event when Backspace is pressed, but this is having no effect.
Question: Is it possible to cancel the Backspace key press using JavaScript or jquery when inside a text box without using readOnly or disabled attribute of textbox?
The code of my demo is also as pasted below.
function keyPressed(e) {
e.preventDefault();
}
function keyUp(e) {
e.preventDefault();
}
#text1 {
width:500px;
}
<input type="text" id="text1" onkeypress="keyPressed(event)"
onkeyup="keyUp(event)" value="This is some text that should not be editable"></input>
I change onkeypress="keyPressed(event)" to onkeydown="keyPressed(event)", it works.
You could use the below code snippet:
$(document).keydown(function (e) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly") || (e.target.getAttribute("type") ==="checkbox")) {
if (e.keyCode === 8) {
return false;
}
}
});
Certain things to keep in mind when implementing such a functionality, you should also be checking for readyOnly textBoxes or textAreas since a backspace in such an area will result in you leaving the page (assuming you want to prevent a backspace as well).
EDIT: The code is in jQuery.
Change your onkeypress event to onkeydown and your code will work with backspace and delete button as well. The onkeyup event is not necessary
<input type="text" id="text1" onkeydown="keyPressed(event)" value="This is some text that should not be editable"></input>
I think you have to trigger the keydown event. But this is a working example. Just give every input you don't want to change the class notEditable and the jquery code will prevent the input field to be edited.
$('.notEditable').on('change keydown', function(e){
e.preventDefault();
});
#text1 {
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1" class="notEditable" value="This is some text that should not be editable"></input>
This code is a little bit cleaner since you only have to add the class and don't need the functions to be called in the html code. However, if you would like to keep the function call in your code, simply change the your input field to this:
<input type="text" id="text1" onkeypress="keyPressed(event)" onkeydown="keyUp(event)" value="This is some text that should not be editable"></input>
Related
I have an HTML form that I'm running with Firefox that looks something like this:
<form name="transfer" id = "transferForm" action='transfer.php' method='POST'>
<div>
<input id="itemSelect" name="itemSelect"/>
<input type="number" name="quantity" id="quantity" value="1"
onkeypress="return isNumberKey(event)"/>
<input type="button" value="Add" id="addButton" style="width:83px"
onclick="addItem()"/>
</div>
<div>
<span id="myForm"></span>
<button id='save' name = 'save' style="width:205px">Save</button>
<button id='transfer' name='transfer' style="width:205px"/>Transfer</button>
</div>
</form>
A few things to note:
-itemSelect is a dojo/dijit combobox that is initialized elsewhere.
-The function addItem(), found in the addButton, runs some javascript that creates new elements in the span myForm each time the add button is clicked. These are processed by transfer.php when the save or transfer button is clicked.
Everything works fine, but I want to add some user friendly controls so the form can work without mouse clicking. I want the user to be able to press 'Enter' when in the "quantity" field, and have the form run the addItem() javascript and move focus back to "itemSelect".
This is the javascript I added. First, to disable the default submit on enter of the form:
<script language="JavaScript">
window.addEventListener('keydown',function(e)
{if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13)
{if(e.target.nodeName=='INPUT'&&e.target.type=='text')
{e.preventDefault();return false;}}},true);
Then I add an event listener to "quantity"
document.getElementById("quantity").addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
//document.getElementById("addButton").click();
addItem(); //Same results using this or the line above
document.getElementById("itemSelect").focus(); //move focus back to the combo box
}
});
</script>
At first glance it appears to work, however I get two different glitches.
With this code in place, if I press enter to run the addItem() function the line gets added on the form between the span tags, but when I click "save" or "transfer" to submit the lines added this way do not not POST. In transfer.php lines that were already added show up (), but any new line added by clicking enter does not go through. However if I just click the "addButton" to add a line instead of pressing enter then it POST's just fine.
When I test adding lines with the keyboard, pressing TAB-ENTER-TAB-ENTER..., it works fine but after on about the 4th cycle the form suddenly submits to transfer.php.
So what could be going wrong with #1, and how does #2 happen?
Try the below:
Remove inline event handlers from your HTML
Seperation of concerns
Know the difference between onKeyPress Vs. onKeyUp and onKeyDown
Stackoverflow question
Prevent form submission on enter:
document.getElementById("transferForm").addEventListener("keypress", function (e) {
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
})
Call addItem on quantity input enter
document.getElementById("quantity").addEventListener("keypress", function (event) {
var keyCode = event.keyCode || event.which;
if (keyCode === 13) {
event.preventDefault();
addItem(); // addItem function call
}
});
call addItem on add button click
document.getElementById("addButton").addEventListener("click", addItem);
function addItem() {
// addItem code
}
Mitigate browser inconsistencies with javascript libraries like jQuery
In your code you might have noticed about getting the keycode value using which.
However jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:
I have an input field:
<input id="audio_file" type="file" accept="audio/*" />
my problem is that once I've clicked it, if I press space after that it simulates the input being clicked again. How do I stop this?
Once clicked, the element gets a keyboard focus. And the next time you press the space bar or enter "click" occurs again. If you need to avoid it, simply remove the keyboard focus of the element using the blur() function.
window.onload = () => {
let input = document.querySelector("input");
input.addEventListener("click", () => input.blur());
}
<html>
<head></head>
<body>
<input type="file" />
</body>
</html>
document.body.onkeyup = function(e){ if(e.keyCode == 32){ } }
Handle space bar press maybe? Then just don't execute any code.
If you'd like to avoid handling keypresses globally, you could use jQuery to prevent the default onClick event for that specific button. Something like:
$("#audio_file").on("click", function(e) {
if (e.originalEvent.detail == 0)
e.preventDefault();
});
Edit: JSFiddle: https://jsfiddle.net/5L01kjkk/
I will demonstrate my problem using the simple example. Consider the following script
$(document).on('keydown','#input1', function(e)
{
if(e.keyCode==13){ $("#input2").focus(); }
});
and HTML
<input type="text" id="input1"/>
<input type="text" id="input2" onkeyup='alert("UP")'/>
every time I press enter in the first input, focus goes to the second input but keyup event is triggered also. I tried stopPropagation but it does not work. How can I prevent that issue?
I'd say you could use keyup instead of keydown
$(document).on('keyup','#input1', function(e)
{
if(e.keyCode==13){ $("#input2").focus(); }
});
jsFiddle Demo
basically I have this:
<asp:TextBox runat='server' />
<button id='b2'>hi</button>
<script>
$('#b2').click(function(e){
e.preventDefault();
alert('you clicked the button');
});
</script>
the problem is that when hitting enter inside the textbox the click event on the b2 occurs so I get the js function executed, anybody knows how to stop this?
Pressing the return/enter key while focusing a text box is treated the same way as clicking on the submit button. What you can do is attach a keypress event handler to all text boxes in your form, and simply ignore the return key press.
Code looks like this:
$('input[type="text"]').keypress(function(event) {
if(event.keyCode == 13) {
event.preventDefault();
alert("enter!");
}
});
Note that I don't use ASP, so I tested this with a standard HTML text box and submit button.
adding the attribute type="button" to the button tag stopped this behavior o_O
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.
<input type="text" id="name" onchange="checkLength(this.value)" />
----onchange does not fire on changing contents of name, but only fires when name goes out of focus.
Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.
I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?
(function () {
var oldVal;
$('#name').on('change textInput input', function () {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
}());
This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.
http://jsfiddle.net/katspaugh/xqeDj/
References:
textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents
A user agent must dispatch this event when one or more characters have
been entered. These characters may originate from a variety of
sources, e.g., characters resulting from a key being pressed or
released on a keyboard device, from the processing of an input method
editor, or resulting from a voice command. Where a “paste” operation
generates a simple sequence of characters, i.e., a text passage
without any structure or style information, this event type should be
generated as well.
input — an HTML5 event type.
Fired at controls when the user changes the value
Firefox, Chrome, IE9 and other modern browsers support it.
This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.
It took me 30 minutes to find it, but this is working in June 2019.
<input type="text" id="myInput" oninput="myFunction()">
and if you want to add an event listener programmatically in js
inputElement.addEventListener("input", event => {})
As an extention to katspaugh's answer, here's a way to do it for multiple elements using a css class.
$('.myclass').each(function(){
$(this).attr('oldval',$(this).val());
});
$('.myclass').on('change keypress paste focus textInput input',function(){
var val = $(this).val();
if(val != $(this).attr('oldval') ){
$(this).attr('oldval',val);
checkLength($(this).val());
}
});
Do it the jQuery way:
<input type="text" id="name" name="name"/>
$('#name').keyup(function() {
alert('Content length has changed to: '+$(this).val().length);
});
You can use onkeyup
<input id="name" onkeyup="checkLength(this.value)" />
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.
<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
Here is another solution I develop for the same problem. However I use many input boxes so I keep old value as an user-defined attribute of the elements itself: "data-value". Using jQuery it is so easy to manage.
$(document).delegate('.filterBox', 'keyup', { self: this }, function (e) {
var self = e.data.self;
if (e.keyCode == 13) {
e.preventDefault();
$(this).attr('data-value', $(this).val());
self.filterBy(this, true)
}
else if (e.keyCode == 27) {
$(this).val('');
$(this).attr('data-value', '');
self.filterBy(this, true)
}
else {
if ($(this).attr('data-value') != $(this).val()) {
$(this).attr('data-value', $(this).val());
self.filterBy(this);
}
}
});
here is, I used 5-6 input boxes have class 'filterBox',
I make filterBy method run only if data-value is different than its own value.