onkeydown doesn't work with javascript - javascript

why doesn't my function return an alert given this particular code?
function searchString() {
if (event.keyCode == alert("Success!"); }
}
Here is my HTML code:
<input type="text" id="searchString" name="searchString" onkeydown="searchString();"/>

You need to pass the event argument in your function. Otherwise event is undefined when you try to invoke the keyCode method:
function searchString(event) {
if(event.keyCode == 13) {
alert("Success!");
}
}
document.querySelector('input').addEventListener('keyup', searchString);
function searchString(event) {
if (event.keyCode == 13) {
alert("Success!");
}
}
<p>Press the <b>enter</b> key in the input below see your alert</p>
<input type="text" />

You can do it with pure javascript:
const search = document.getElementById('searchString');
search.addEventListener('keydown', (e) => {
if (e.keyCode === 13) {
// your code here
}
}
Note: 13 is the key code for the enter

You need to ensure that the actual event is being passed as an argument... otherwise, it will be unrecognised within the function. To see which code is tied to which key, please try the following.
function check(event)
{
var keycode = event.keyCode;
alert(keycode);
}
And then ...
<input type="text" id="check" name="check" onkeydown="check();">
The return key is tied with '13'. So if you just want to do something when it is pressed, do the following.
function searchString(event)
{
if(event.keyCode === 13) {
alert("return key was pressed");
// do something ....
}
}
And the html code should be something like the following.
<input type="text" id="searchString" name="searchString" onkeydown="searchString();">
Please note that I have used '===' instead of '=='. It is now the recommended practise. Also, note that the forward slash at the end of input is not necessary.

Related

Automatic keypress on page load

I have an input area where a value has been preset. I would like to make it so that on page-load the "enter" button is pressed on the keyboard to submit the value.
Here is the code:
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
}
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
A solution where I would not need to press enter and the value is submitted is also welcome!
I guess code below would work.
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
console.log('triggered')
player_name = $(this).val();
logged = 1;
}
})
const event = new Event('keypress')
event.which = 13
document.querySelector('#login-input').dispatchEvent(event)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
The doc
If you want it to run after page loaded, use onload event. The solution may look like this:
<script>
function f() {
// Test it:
// alert("Hello, page loaded!");
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="f()">
If you do want user to have a glimpse on your pre-filled login form and inform about what is happening, you may make a delay with setTimeout function, which will fire in 0.5 sec after onload event happened.
<script>
function f() {
$('#some_element').text('Signing you in...');
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="setTimeout(f, 500)">
Or you can call the event handler with a faked keypress like this:
function kpress(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
console.log(player_name,logged);
}
}
kpress.call($('#login-input').keypress(kpress),{which:13});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
I use the output from the jQuery event binding as the object context for the Function.prototype.call() method and add a "simplified" event object as {which:13}.

check input field value on enter press against js object value

My input field <input type="text" id="barcode" placeholder="Barcode"
onkeypress="search(this)">
and I want to check it's value by pressing enter against a value in my js object.
function search(ele) {
if(event.key === 'Enter') {
// element.anr is the value i want to check my input against
if (ele.value === element.anr) {
// action that should be performed if value is equal
document.getElementById("next").click();
}
}
};
What am I doing wrong here? Nothing happens when I put the correct value and hit enter (sidenote the document.getElementById("next").click(); is showing me the next key and its values of my js object)
just tested element.anr as 123 and tried, its working fine
function search(ele) {
if(event.key === 'Enter') {
var anr="123"
// element.anr is the value i want to check my input against
if (ele.value == anr) {
// action that should be performed if value is equal
console.log(ele.value+" - "+anr);
document.getElementById("next").click();
}
}
}
function printHi()
{
console.log("HAIIIII")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="barcode" placeholder="Barcode"
onkeypress="search(this)">
<button id="next" onclick="printHi();">test</button>
You can use an eventListeners,
const node = document.getElementsById("barcode");
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});

How to prevent invalid characters from being typed into input fields

Onkeydown, I run the following JavaScript:
function ThisOnKeyDown(el) {
if (el.title == 'textonly') {
!(/^[A-Za-zÑñ-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ-\s]/ig, '') : null;
}
if (el.title == 'numbersonly') {
!(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
}
if (el.title == 'textandnumbers') {
!(/^[A-Za-zÑñ0-9-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ0-9-\s]/ig, '') : null;
}
}
One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!
Edit: I create the events globally. Here's how I do that:
function Globalization() {
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
inputs[i].onfocus = createEventHandler(
ThisOnFocus, inputs[i]);
inputs[i].onblur = createEventHandler(
ThisOnBlur, inputs[i]);
inputs[i].onkeydown = createEventHandler(
ThisOnKeyDown, inputs[i]);
inputs[i].onkeyup = createEventHandler(
ThisOnKeyUp, inputs[i]);
}
}
Globalization() is run body.onload
Therefore, a typical input field has HTML without function calls like this:
<input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>
To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.
I wrote the example below using jQuery, but you can use the same function when binding traditionally.
Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.
$("input.number-only").bind({
keydown: function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
});
The above code does it says- allows ONLY numbers. You can modify it by adding exception to say BACKSPACE for example like this
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charValue= String.fromCharCode(e.keyCode);
if((isNaN(charValue)) && (e.which != 8 )){ // BSP KB code is 8
e.preventDefault();
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
$('.key-filter').keypress(function () {
if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();
});
then add the key-filter class to your input if using jquery
or
<input type="text" onkeypress="if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();" />
just put the charaters you want to allow inside the [] after the ^.
this allows all letters numbers _ - and .
You can replace your input value during the "input" event :
// <input oninput=onInput(event) />
const onInput = event => {
event.target.value = event.target.value.replace(/[^0-9+]/g, '')
}
source : https://knplabs.com/en/blog/how2-tips-how-to-restrict-allowed-characters-inside-a-text-input-in-one-line-of-code
i found this solution in: http://help.dottoro.com/ljlkwans.php
works as intended.
<script type="text/javascript">
function FilterInput (event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0 */ && keyCode <= 105 /* KeyboardEvent.DOM_VK_NUMPAD9 */);
modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
}
</script>
< body>
The following text field does not accept numeric input:
<input type="text" onkeydown="return FilterInput (event)" />< /body>
it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return
Code is useful for preventing user from typing any other character except number.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval)){
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
You could easily do this in a single html line.
Like this to disallow spaces:
<input type="text" onkeypress="return event.charCode != 32">
Or this to only allow numbers:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
Just look up the unicode of any numbers you want to allow or disallow.
Run your code against the onkeyup event and not the onkeydown event. This way you can access the result of the very last keystroke where as the onkeyup event executes as a key is pressed without knowing its result.

Stop the ENTER key from being used in a dojo textarea dijit?

i am trying to limit the height of the dojo's dijit.Textarea by preventing users from hitting the enter key while typing. How can i prevent the enter key from being used? i have the below code but its not wroking.
<input type="text" dojoType="dijit.form.Textarea" maxLength="99" onkeydown="return noEnter" />
function noEnter(evt) { if (evt.keyCode == dojo.keys.ENTER) {
console.log('enter pressed');
evt.stopPropagation();
return false; }else{
console.log(evt.keyCode + ' pressed');
return true; }}
Dojo has a method that can be used for this purpose called stopEvent. Perhaps you could use it like this:
<input type="text" dojoType="dijit.form.Textarea" maxLength="99" onkeydown="noEnter" />
function noEnter(e){
if(e.keyCode == dojo.keys.ENTER){
dojo.stopEvent(e);
}
}
Use a dijit.form.SimpleTextarea which is a straight replacement for <textarea>, that is: it does not automatically adjust the height.

HDI: Disable postback on html input box

I have an input box that I don't want postback to occur on someone striking the enter key
I want the javascript event to take place instead.
<input
type="text"
id="addressInput"
onkeydown="inputenter()"
autopostback="false"/>
function inputenter() {
if (event.keyCode == 13) {
seachLocations();
return false;
}
else {
return false;
}
}
Just return false form JS function, add return false; at the end of function.
or <input type="text"
id="addressInput"
onkeydown ="return (event.keyCode!=13)"
autopostback="false"/>
UPDATE:
How about this..?
<asp:TextBox ID="TextBox1" runat="server"
onkeydown="return CallEnterKeyFunc(event.keyCode);">
</asp:TextBox>
<script type="text/javascript">
function CallEnterKeyFunc(key) {
if (key == 13) { //for FF, i think you have to use evt.which
//enter key press
seachLocations();
return false;
}
else
return true;
}
function seachLocations() {
//your code
alert("hello");
}
</script>
Special thanks to: http://www.beansoftware.com/ASP.NET-Tutorials/Accept-Enter-Key.aspx
<input type="text" id="addressInput" onkeydown="if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
searchLocations();
}" />

Categories

Resources