How can I simulate a keypress to an input, using vanilla javascript?
I have tested every possible answer on SO and elsewhere, and it doesn't work on Chrome or Firefox.
For example, let's say we have a form:
<input id="myInput" type="text">
<button id="myButton>Click Me</button>
How could I make it so that when the button is clicked, the letter "a" is added to the input?
You'd first add a keyup event listener to the document object and inside the callback you assign the value of the input via value depending on which key was pressed:
var input = document.getElementById("myInput");
document.addEventListener('keyup', function(e) {
if (e.which === 39 || e.which === 19) {
input.value += 'a';
}
});
<input id="myInput" type="text" />
<button id="myButton">Click Me</button>
This way works i think:
<html>
<body>
<input type="text" id="myText" placeholder=" ">
<button id="but1" onclick="myFunctionA()">A</button>
<button id="but2" onclick="myFunctionB()">B</button>
<script>
function myFunctionA() {
document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "A";
}
function myFunctionB() {
document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "B";
}
//And so on
</script>
</body>
</html>
Any doubts tell me
Related
I have a search box which should work with pressing the button and also pressing the Enter key. They both have the same code.
The button works perfectly but when it comes to the Enter key, most of the time it doesn't work and sometimes it suddenly works.
Here's my code:
$(document).ready(function() {
function myFunction() {
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
});
}
$('#search').click(function() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" onkeydown="myFunction()" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
You are adding both an onKeyDown attribute to your HTML and attaching an event listener. So what's happening is that when your key down occurs, it's calling myFunction, which attaches a second event handler for keydown. The second time around the enter key behavior might kick in, but because each keydown attaches a new event listener, you might have the logic kick in multiple times.
Choose one approach or the other. Either use the HTML attribute or add the event listener programmatically, but not both.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
JS:
$(document).ready(function() {
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
doSearch();
event.preventDefault();
}
});
$('#search').click(function() {
doSearch();
});
function doSearch() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
});
(note I also added a .preventDefault() to make sure that the default behavior of the enter key doesn't kick in, since it may submit your form)
Edit:
Moved duplicated code into its own function.
Remove the inline-event onkeydown you don't need it.
You need to use preventDefault inside your myFunction function.
Remove the classes inside your functions to see clearly the new search result.
$(document).ready(function() {
$("#search-criteria").keypress(function(event) {
if (event.which === 13) {
myFunction();
}
});
//code for the button
$('#search').click(myFunction);
});
var myFunction = function() {
event.preventDefault();
var txt = $('#search-criteria').val();
$('.items').removeClass('searched');
$('.items:contains("' + txt + '")').addClass('searched');
}
.searched {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
<ul>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
</ul>
I made a couple of small changes to the code you posted and it is working well for me as a snippet.
I documented the changes in the code itself.
$(document).ready(function() {
//code for Enter key
function myFunction() {
console.log("myFunction called");
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
// Keep the ENTER key from submitting the form.
event.preventDefault();
myFunction();
}
});
//code for the button
$('#search').click(function() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form>
<!--
the `onkeydown` on this can't work, since 'myfunction' isn't in the global space
so I removed it.
-->
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}
I have this button that leads to a method in javascript that filters the information of a table:
<button type="button" id="search" title="Buscar" onclick="fn_cliente.filtraInformacion();"></button>
There are several fields for which you can filter the information, I want that when pressing "enter" on any input, it executes the same method as when clicking on the button
Use the following to bind the enter event to your search fields.
document.querySelectorAll('.searchfield').forEach(function(input) {
input.addEventListener('keypress', function(e) {
if (e.keyCode === 13) filtraInformacion();
});
});
Look at this code snippet
function filtraInformacion() {
console.log('filtraInformacion has been called!');
}
document.querySelectorAll('.searchfield').forEach(function(input) {
input.addEventListener('keypress', function(e) {
if (e.keyCode === 13) filtraInformacion();
});
});
<button type="button" id="search" title="Buscar" onclick="filtraInformacion();">Click me</button>
<br>
<input id='name' class='searchfield' placeholder='Press Enter!'>
<br>
<input id='lastname' class='searchfield' placeholder='Press Enter!'><br>
<input id='gender' class='searchfield' placeholder='Press Enter!'>
See? when the enter key is pressed, the function filtraInformacion is called.
This works. You can adapt it to whatever element you want.
<input type="text" id="account-location-country-input" class="mdc-text-field__input" required onkeyup = "if (event.keyCode == 13)document.getElementById('edit-account-button').click()">
I have javascript that will fire an alert box when the enter key is pressed within a telerik RadAutoCompleteBox. When enter is pressed i need to find the nearest asp.net (input button) and click this. Any Suggestions?
<script>
$(document).ready(function () {
var handler = Telerik.Web.UI.RadAutoCompleteBox.prototype._onKeyDown;
Telerik.Web.UI.RadAutoCompleteBox.prototype._onKeyDown = function (e) {
handler.apply(this, [e]); // Let AutoCompleteBox finish it's internal logic
if (e.keyCode == Sys.UI.Key.enter) {
this._onBlur();
alert('Enter has been pressed inside RadAutoCompleteBox');
}
}
});
</script>
I'm not sure this is what you are looking for since it requires jQuery, at any rate here are 2 options. One going through a parent element and then looking through the child elements, the second if they are on the same level through siblings.
$('#textbox').on('keyup', function() {
$(this).parent().find('input[type="button"]').click();
});
$('#thebutton').on('click', function() {
alert('the click happened');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<input type="text" id="textbox">
<input type="button" id="thebutton" value="click me">
</div>
$('#textbox').on('keyup', function() {
$(this).siblings('input[type="button"]').click();
});
$('#thebutton').on('click', function() {
alert('the click happened');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox">
<input type="button" id="thebutton" value="click me">
You can use closest() to find the nearest "button type" input or button tag
if (e.keyCode == Sys.UI.Key.enter) {
// Code
var input = $(e.target).closest('input[type="button"],input[type="submit"],button');
if (input.lenght > 0) {
input.click();
}
}
This will search the element itself and later will traverse up through its ancestors in the DOM tree to find the first match and click it
When I use jquery to clear content of input:
$('input#myinput').val('');
everything is fine except for the user cannot use ctrl+z to obtain the previous text. is there any way to preserve ctrl+z ?
is there any way behaves as if it is cleared by user?
Suppose it gets cleared on clicking a button:
$(document).ready(function() {
var input = $('input#myinput').val();
$('#button').click(function() {
$('input#myinput').val('');
});
$(document).keydown(function(e) {
if (e.which === 90 && e.ctrlKey) {
$('input#myinput').val( input );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myinput" value="text"/>
<input type="button" id="button" value="Button" />