jQuery keyup should should trigger enter key - javascript

I have a simple problem (hopefully), but I am unable to find a clear solution.
I have a datatable, which has a text input field. The user enters text into the text field, and hits the enter key. This automatically filters from the text entered.
I was hoping to use the onkeyup event to trigger so when a user enters a value in the text field, the datatable automatically updates, rather than the user having to press enter.
<input type="text" name="input" class="filter" id="input" onkeyup="functionName(this)" value="">
<script>
function functionName(e) {
alert(e.value);
}
</script>
This code works, so when I enter a value, it pops an alert up displaying the entered value.
Is it possible i can change the alert, to do a submit, or replicate what the "enter" key does.
From trying to find a solution, it is more difficult because it is not a form, as it uses ajax so the .submit methods will not work.
I was also hoping a solution like this could work
<script>
var e = jQuery.Event("keyup");
e.which = 13; // Enter
$("#input").trigger(e);
</script>
I know there are many similar topics, and I have looked, but none of them seem to be the right solution for me.
Thanks for the help.
//
Edit
//
Based on the keyup issue, how can I refocus cursor after filtering. Is this done at the same time as filtering?
$obj.find('input.filter').on('keyup',function(e){
e.preventDefault();
ajax($obj);
});

You're using jQuery, so there's no real need to use onclick="", Secondly try to avoid to use reserved names for IDs & Classes (e.g. #input). Lastly, you can mimic the form submission by using $.post() on each .keyup event like below:
<input type="text" name="input" class="filter" id="searchinput" value="" />
<script>
$(document).ready(function() {
$(document).on('keyup', '.filter', function( event ) {
$.post( 'yourapi.php', { input: $(this).val() }, function( data ) {
//Refocus the <input />
$('#searchinput').focus();
});
});
});
</script>

As you can code in jquery too. Then you can go with this code......
$(document).ready(function(){
$(".filter").keyup(function(){
var text_input_text = $(this).val();
//here is your ajax post request
$.post('url for post', {filter_text: text_input_text}, function(response){
console.log(response);
});
});
});
Here we have covered the keyup event and ajax post.
Hope this will help you.

$(document).ready(function(){
$("input").keyup(function(event)
{
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode != '13')
{
var e = jQuery.Event("keyup");
e.which = 13; // Enter
$("input").trigger(e);
}
else {alert("Enter triggered");
}
});
});
DEMO JSFiddle

Related

On ENTER keyup - Execute Function inside form and not submit the form

I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.
Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button. There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.
I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting. I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"
$("#addTitle").on('keyup', function(e){
var keyCode = e.keyCode || e.which;
console.log('keyup');
if (keyCode == 13){
console.log('ENTER PRESSED');
if ($("#dataTables_filter_input").is(":focus")){
console.log('FILTER FOCUS');
tableFilter();
e.preventDefault();
return false;
}
}
});
I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.
Do I have things out of order? Am I not calling the right functions?
we must know the mechanical first.
<form>
<input type="text">
<input type="submit">
</form>
if you pressed ENTER in input text. it will trigger:
button submit clicked
form submitted
input text keyup [ENTER]
if you want prevent default behaviour. You must use preventDefault() on $('form').submit [only], in other word you dont need type preventDefault() in $('input[type="submit"]').click or $('input[type="text"]').keyup
so, your jquery will like this
$('form').submit(function(e){
e.preventDefault();
})
$('input[type="text"]').keyup(function(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 13){
//do something
}
})
but you will never can use submit button to trigger form input. To do form submit you must use type="button" to trigger form submit.
Demo: http://jsbin.com/pirepahuhu/edit?html,output
===============
this what i think to force solved this problem
demo: http://jsbin.com/hiqatetoti/2/edit?html,output
<form>
another text input<input type="text"><br>
add title<input type="text" id="addTitle"><br>
another text input<input type="text"><br>
<input type="button" value="button"><br>
<input type="submit" value="submit"><br>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<Script>
$(function(){
$("#addTitle").on('keyup', function(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 13){
console.log("ENTER PRESSED on input text");
}
});
$('form').submit(function(e){
e.preventDefault();
if($(this).find('#addTitle').is(':focus') === false){
doAjaxForm();
}
});
function doAjaxForm(){
console.log('do ajax form');
}
})
</script>
if form submitted but #addTitle has focused = do nothing, then addTtitle keyup will do your job
if form submitted but #addTitle not focussed = do ajax form
if you press enter on another text input (except #addTitle) , this will trigger form submit = do ajax form
if submit button clicked = do ajax form
i hope this will work for you, since you dont give us your datatables script.
let cancelEvent = function (e) {
e.preventDefault();
return false;
};
let filter = document.getElementById('dataTables_filter_input');
let addTitle = document.getElementById('addTitle');
let form = document.querySelector('form');
form.addEventListener('submit', cancelEvent);
addTitle.addEventListener('keyup', function(e) {
let keyCode = e.keyCode || e.which;
console.log('KEYUP');
if (keyCode !== 13 || !filter.is(':focus')) {
console.log('NOT ENTER PRESSED OR FILTER NOT FOCUS');
return true;
}
tableFilter();
e.preventDefault();
return false;
});

Keep focus on input type text/search on keypress

I've written a simple input of type text, but when I press enter while my cursor is inside the textbox, it looses the focus. How can I ignore enter key to stop losing focus from the text box? I tried doing something like this:
<input type="text" (keyup)="keepFocus($event)" />
and keepFocus() is a method:
keepFocus(e) {
e.target.select();
}
But this method is called everytime I press a key, which is not very efficient. Is there a better solution to handle this behavior?
You capture just the enter key, and prevent default when it's pressed
document.getElementById('myInput').addEventListener('keypress', function(event) {
if (event.which === 13) event.preventDefault();
});
<input type="text" id="myInput" />
Another way to do this is by getting the keyCode (that e parameter use).
I mean, use this:
http://www.javascripter.net/faq/keycodes.htm
And this:
https://www.w3schools.com/jsreF/event_preventdefault.asp
Something like this would be fine:
function keepFocus(e) {
if(e.keyCode == 13)
e.preventDefault();
}
<input type="text" keyup="keepFocus" />
This will prevent that you lost the focus when enter key is pressed!
There are two ways to do the job.
First, reput the focus to the input when the user click "Enter":
<input type="text" onkeyup="keepFocus(event);" id="teste" />
function keepFocus(e) {
if (e.key=="Enter") {
var teste = document.getElementById ("teste");
teste.focus ();
}
}
Second, prevent the default behavior of the text field:
function keepFocus(e) {
if (e.key=="Enter") {
e.preventDefault ();
}
}
I think the second way is better because you do not have to add an id to your input.

jQuery keypress enter not working

I tried to use keypress to get an text from to update a text in . My html looks like this:
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag"></input>
</form>
</div>
My jQuery looks like this:
$(document).ready(function () {
$("input").keypress(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
}
}
);
})
My console log doesn't log on first keypress, how can I help it? Also my "hello" never log. Any ideas why this is happening?
Thanks!
Use keyup event to capture first keyboard char.
$(document).ready(function () {
$("input").keyup(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
alert('hello');
}
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>
Note: Hitting Enter key will submit the form and it will redirect the page. You might not see the console message for "hello"
The keypress function fires right as a key is pressed. You want to use keyup as that will fire when the key is released.
You need to use keyup as keypress will trigger value as soon as a key is pressed which is separate from releasing a key.
There are few changes that can be done. input is a self closing tag. Also it is better to use $(this) inside the function as it will get the value only from the input from where the event is triggered.
There may be a catch here. On pressing enter/return key you may see the form is getting submitted
$(document).ready(function() {
$("input").keyup(function(e) {
var currentInput = $(this).val();
console.log(currentInput);
if (e.keyCode == 13) {
console.log('hello');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>

javascript keypress multiple records problems

I would like to ask why it will have multiple response? How can i enter the input field with just one response?
Expectation : Input the data in input field and press the enter , it will execute the actions.
$("#textInput").keypress(function (e) {
console.log("123");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type='text' id='textInput'/>
You have syntax error in you code. closing should be }); instead of )};
$("#textInput").keypress(function (e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textInput">
Expectation : Input the data in input field and press the enter , it will execute the actions.
In order to submit the corresponding form as soon as the user enters a text string and a final enter key you can:
test if current char is the enter key (e.which == 13)
get the closest form
submit the form
$("#textInput").on('keypress', function (e) {
if (e.which == 13) {
$(this).closest('form').submit();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/action_page.php">
Enter text and type enter to submit:<br>
<input type="text" name="textInput" value="">
</form>
I think, you should have choose other event,like onblur to fix your problem
$("#textInput").on('blur',function (e) {
console.log("123");
)};
In your code ,keypress events gives you output,in every keypress action,So this is the reason you got multiple responses
And next,if you think,if you want to press Enter button then need response,In this case little changes will helps you
$("#textInput").keypress(function (e) {
if(e.which == 13) {
console.log("123");
}
});
The keypress event is sent to an element when the browser registers keyboard input.
— jQuery Documentation link
What you really want is .submit() as they are the one that will only be triggered when the user submits info.
$("#textInput").submit(function (e) {
console.log("123");
)};
Or if you only want to detect enter keypress but not submit, use this:
How to detect pressing Enter on keyboard using jQuery?

Stop Enter/Return key submitting a form [duplicate]

This question already has answers here:
Prevent users from submitting a form by hitting Enter
(36 answers)
Closed 6 years ago.
I have a table within a form. The table contains some form fields, but there are form fields outside of the table (but still within the form) too.
I know that Enter and Return are traditionally used to submit a form via the keyboard, but I want to stop this behaviour for fields within the table. For example, if I focus a field within the table and hit Enter/Return, nothing happens. If I focus a field outside of the table (but still within the form) then for it to submit as normal.
I have a jQuery plugin that targets this table. Simplified, this is what I've tried this far:
base.on('keydown', function(e) {
if (e.keyCode == 13) {
e.stopPropagation();
return false;
}
});
Where base is the table jQuery object. This is within my plugin's init method. However, hitting Enter still submits the form.
Where am I going wrong?
EDIT: Some simplified HTML:
<form method="" action="">
<input type="text" /><!--this should still submit on Enter-->
<table>
<tbody>
<tr>
<td>
<input type="text" /><!--this should NOT submit on Enter-->
</td>
</tr>
</tbody>
</table>
</form>
base.keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
or for only inputs:
$(':input', base).keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13)
return false;
});
I'm going to guess that a form element will fire the submit event, it doesn't bubble up through the table and on to the form, try this instread:
$('input, select, textarea', base).on('keydown', function(e) {
if (e.keyCode == 13) {
return false;
}
});
Note we're also providing context to the selector, so this keyDown will only occur on elements (modify as required) within your table.
As gordan said in another comment, return false does both .preventDefault() and .stopPropagation()
e.preventDefault() rather than e.stopPropagation(). stopPropagation only stops it bubbling up to higher DOM nodes, it doesn't prevent the default action.
I found this Q/A trying to sort out a similar situation where I have multiple forms and enter would not do what I wanted. In my specific case, I would dynamically add a new <div id="D1"> D1, D2, D3, etc, and each new div has a form that would reload that div from the same php code that created it, only also with a POST.
Unrelated first problem was I couldn't dynamically create a new function with each div, so I passed the D1, etc, descriptor as an argument to the Javascript function:
<script type="text/javascript">
function formSubmit ( divid ) {
// post data
event.preventDefault();
$.post( "make-my-form-div.php",
$("#form"+divid).serialize(),
function(data){
$("#"+divid).html(data);
});
return false;
}
</script>
You will see the requisite event.preventDefault(); and return false; that works for the answers in this thread. It didn't work for me. If I click the Submit in any one form, that one div would reload with the correct data. Hitting enter would cause default action and reload the entire page, leaving me with only 1 div.
This Answer worked: I needed a unique ID and NAME for the different forms. Initially, they were <INPUT TYPE="button" VALUE="Submit" onClick="formSubmit('<?php echo $divid ?>');"> but once I added unique ID and NAMES, such as "formD1", etc, it all started working correctly.
This works for me.
$("input[type='text']").on('keypress', function(e) { return e.keyCode != 13; });
Just put below code in your template file or in header of page.
<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>

Categories

Resources