Automatic keypress on page load - javascript

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}.

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Do a function if specific word is submitted in textbox

how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work
Heres the code
<form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)">
</form>
<div id="canvasDiv" width="500" height="10"></div>
<script type="text/javascript" src="robotti.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 500, 500);
document.getElementById("canvasDiv").onmousedown = function() {
jump(); }
//document.getElementById("canvasDiv").onkeypress = function() {
//move(); }
document.getElementById("canvasDiv").window.onkeypress = function(event) {
if (event.keyCode == 41) {
move();
}
}
</script>
This should work -:
var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
jump();
getElementById("canvasDiv").value = "";
}
Please use onkeyup instead of onkeydown
<!DOCTYPE html>
<html>
<body>
<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">
<script>
function keyCode(e) {
var text = (document.getElementById("canvasDiv").value).toLowerCase();
if(text == 'jump' || text == 'move'){
//call jump function here
alert("jump");
}
}
</script>
</body>
</html>
You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.
document.querySelector('input[type="text"]').addEventListener('keyup', function() {
switch (this.value) {
case 'move':
console.log('move!'); // Your actual function here
this.value = ''; // Reset value
break;
case 'jump':
console.log('jump!'); // Your actual function here
this.value = '' // Reset value
break;
}
});
Command the robot!: <input type="text" size="50">
Further reading:
Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector

dynamic textbox in pressing enter key

can someone help me with my code? everytime I type in my textbox it create multiple textbox but I want to create a program that everytime I hit enter key it create another textbox.
here's my code:
<script language="javascript">
function changeIt() {
var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i><br/>"
}
</script>
<body>
<form name="form" action="post" method="">
<input type="text" name=t1 onkeydown="changeIt()">
<div id="my_div"></div>
</form>
</body>
See this fiddle
What you have done in your code was to create a textfield whenever a key press occurs..To create a textfield only when enter key is pressed you have to check the keycode of the pressed button.
So, Please change your JS a little bit as follows..
function changeIt(event) {
var key = event.which || event.keyCode;
if (key == '13') {
var i = 1;
my_div.innerHTML = my_div.innerHTML + "<br><input type='text' name='mytext'+ i><br/>"
}
}
Please make sure that you replace your <input> also as follows
<input type="text" name=t1 onkeydown="changeIt(event)">
Please read more about keyCode in the docs.. Also, if you want to find out the keyCode of any button, please check keycode.info
Your current JS function is being execute every time a button is pressed because you're use the event onkeydown which will capture any key pressing.
Do this:
<script>
var changed = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
/* YOUR EXECUTION CODE */
}
}
</script>
<form name="form" action="post" method="">
<input type="text" name="t1">
<div id="my_div"></div>
</form>
You are creating a new <input> everytime any key is pressed. Instead, you should check if Enter was pressed using e.key or e.code (note both e.which and e.keyCode are depreacted).
Also, consider using Node.appendChild() instead of innerHTML. Otherwise, every time you add a new <input>, all the existing ones will be re-created and lose their values.
const input = document.getElementById('input');
const inputs = document.getElementById('inputs');
input.addEventListener('keydown', ({ key }) => {
if (key !== 'Enter') return;
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = `mytext${ inputs.children.length }`;
inputs.appendChild(newInput);
});
input {
display: block;
}
<form name="form" action="post" method="">
<input type="text" id="input">
<div id="inputs"></div>
</form>
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode, you can use https://keyjs.dev:
Disclaimer: I'm the author.

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

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.

Categories

Resources