Making the enter key function like tab key - javascript

Friends ,I know there are already many solutions to this question and i have used one but for some unknown reason it is not working in my application.So please help me out and let me know where am i going wrong.Please don't mark this question as duplicate.I seriously need your help.
Thanks in advance.
here is what i have tried.
// Catch the keydown for the entire document
$(document).keydown(function(e) {
// Set self as the current item in focus
var self = $(':focus'),
// Set the form by the current item in focus
form = self.parents('form:eq(0)'),
focusable;
// Array of Indexable/Tab-able items
focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
function enterKey(){
if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
// If not a regular hyperlink/button/textarea
if ($.inArray(self, focusable) && (!self.is('a,button'))){
// Then prevent the default [Enter] key behaviour from submitting the form
e.preventDefault();
} // Otherwise follow the link/button as by design, or put new line in textarea
// Focus on the next item (either previous or next depending on shift)
focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
return false;
}
}
// We need to capture the [Shift] key and check the [Enter] key either way.
if (e.shiftKey) { enterKey() } else { enterKey() }
});
html code-
<form id="purchase" action="p_senddata.php" method="POST" >
Bill_no:<input type="text" name="p_billno" id="pbillno" /><br />
Date:<input type="text" name="p_date" id="pdate" /><br />
Name of party:<input type="text" name="p_nameofparty" id="pnameofparty" /><br /><br />
<input type="submit">
</form>

Related

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Enable submit when all form items are valid

I need some help with something... say I have the following form...
<form name="" id="" method="" action="">
<input type="text" id="text1" name="text1" />
<br />
<br />
<input type="text" id="text2" name="text2" />
<br />
<br />
<input type="text" id="text3" name="text3" />
<br />
<br />
<input type="text" id="text4" name="text4" />
<br />
<br />
<input type="submit" value="let's go" disabled="disabled" />
</form>
Now I want to have a simple script to enable the submit when the values of the text boxes are not an empty string or null...
So I have something like this.. which I will bind to the window.onload
function enableButton(){
var formitemsArray = ['text1','text2','text3','text4'],
i;
// Loop through all items
for(i=0;i<formitemsArray.length;i++){
// validate the length on the keypress...
formitemsArray.onkeypress = function(){
// loop through all the items again
for(j=0;j<formitemsArray.length;j++){
if(formitemsArray[j] == "" || formitemsArray[j] == null ){
// return false or something???
}else{
document.getElementById("submitButton").disabled = false;
}
}
}
}
}
Now I think I'm on the right lines to a solution but I'm getting lost when trying to make sure that all the items are greater than a zero length string as I'm returning false too soon. Can someone set me straight please?
Welcome to event bubbling!
This does the following: listen to an event (onkeypress) on the whole element and all its children! Which means you can do the following:
document.getElementById('form-id').onkeypress = function(e) {
var text1 = document.getElementById('text1'),
text2 = document.getElementById('text2'),
text3 = document.getElementById('text3'),
text4 = document.getElementById('text4')
if (text1.value.length > 0 &&
text2.value.length > 0 &&
text3.value.length > 0 &&
text4.value.length > 0) {
document.getElementById('submit-button').disabled = false
}
// As an aside, for later: if you want to get the element
// that triggered the event, you have to do the following
// to be cross-browser:
var evt = e || window.event, // IE doesn't get the event passed by argument
target = e.target || e.srcElement // 'target' is official, old versions of FF used 'srcElement'
// With the 'target' variable, you can now play.
}
There is another more generic solution, but it might not fit your needs (note that it requires a forEach shim:
// Declare a counter variable
var count = 0
document.getElementById('form-id').onkeypress = function(e) {
// Get all the inputs!
var inputs = this.getElementsByTagName('input')
// Now loop through all those inputs
// Since a NodeList doesn't have the forEach method, let's borrow it from an array!
[].forEach.call(inputs, loopThroughInputs)
}
function loopThroughInputs(input) {
// First check the type of the input
if (input.type === 'text') {
// If the value is correct, increase the counter
if (input.value.length > 0) {
count++
}
// If the 4 inputs have increased the counter, it's alright!
if (count === 4) {
document.getElementById('submit-button').disabled = false
}
}
}
And now this code was proposed by #Esailija, and it is way better and cleaner. However, it also requires ES5-Shim (for the every method):
document.getElementById('form-id').onkeypress = function(e) {
var inputs = [].slice.call( this.querySelectorAll( '[type=text]') );
document.getElementById('submit-button').disabled = !inputs.every(function(input){
return !!input.value;
});
}
(This guy is brillant, just don't tell him)
There are a few ways you can do this... One would be to keep the button enabled but use javascript to check the validity of the form data upon submission. The benefit to this is that the validation code is only run once, when the user clicks submit and is expecting his data to be validated (at least I do) .
function validateForm() {
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
if( formElement.elements[i].value.length === 0 ) {
return false;
}
return true;
}
}
The other way is live validation, which would validate each input onBlur (focus lost). This method has the benefit of showing the user in real time what values are bad, however this can be very resource heavy depending on the number of form elements and the way you introduce the check.
Personally I would go with my first suggestion; however with that said if you choose to validate each element, I would do so like this:
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
formElement.elements[i].addEventListener('blur', function() {
if( this.value.length === 0 ) {
alert('this input is invalid');
}
}, false);
}
The latter method also requires you hold onto a 'state' variable to determine whether or not the form is valid upon submission, or check all the values again.
Hope this sheds some light, and I hope my code examples help some.
If possible use jquery validation plugin instead of re-inventing the code, http://docs.jquery.com/Plugins/Validation its so easy to use.
In this jsfiddle you'll find a way to monitor the progress of form contents. If all the field conditions are fulfilled, a submit button is shown. Maybe it's useful for you. Bare in mind that client side checking of a form may be tampered with, so you always need a server side check too, if your data need to adhere to certain requirements. In other words: client side form checks are merely usability enhancements.

Tab button is not working in form text fields

i have a form in which i am using 4 textfields.
textfield1
textfield2
textfield3
textfield4
i am calling a function on "onpress" event on textfield2 and textfield3 for checking only integer values. the function is given below.
function checkIntnumber(obj,event){
var unicode=event.charCode? event.charCode : event.keyCode
if((unicode==37 || unicode==39 || unicode==35 || unicode==36 || unicode==46)
&& event.which==0) {//if the key isn't the (BackSpace/Left Arrow/Right
Arrow/Delete/Home/End) key (which we should allow)
return true;
} else if(unicode!=8) {
if (unicode>=48 && unicode<=57) { //if a number
return true; //enable key press
} else {
return false; //disable key press
}
}
}
now then i move from textfield1 to textfield2 using tab key this is working fine but tab key is not working to move from textfield2 to textfield3 or textfield3 to textfield4. this problem is occuring in mozilla firefox only. please help me.
thanks
EDIT: code from the comment under the answer -
<input type="text" name="from" id="from" style="width:50px;"
onkeypress="hideRateDiv();return checkIntnumber(this,event)"/>
- <input type="text" name="to" id="to" style="width:50px;"
onkeypress="hideRateDiv();return checkIntnumber(this,event)" tabindex="2"/>
You just need to test for the code that corresponds to the tab key (9) and return true.
EDIT: Sorry, just saw Christian's comment and read the question a bit more carefully. There could be a tabindex issue, but there shouldn't be if the four fields are defined right after each other in your source HTML. But given that the code you posted doesn't seem to allow the tab key I don't understand how tabbing would work between your field 1 and 2 - it shouldn't work between any of them.
Can you please post the HTML for those fields and show how you assign the keypress event?
if((unicode==37 || unicode==39 || unicode==35 || unicode==36 || unicode==46 || unicode==9) && event.which==0) Change the if condition like this, keycode for tab also (that is 9)

how to auto press "tab" key when user press "-" (dash) key in javascript

my code like this
function Tab(e)
{
var input = e.keyCode ? e.keyCode : e.charCode;
if ((input>=48 && input<=57) || (input==45))
{
if (input==45)
{
//what should i do here? so,
//if user press "-", its auto tab to next textfield,
return false
}
else
return true;
}
else
return false;
}
here my html
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
I've been searching at google. but its return similar article and it's not that I'm looking for.
I have a lot of similar text field, so it is not possible to include the next textfield's name cause of i used array name.
sorry if my english is bad, but i hope you understand what I want
You can focus the next input sibling in this way:
HTML:
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
JS:
function Tab(e, inp)
{
var input = e.keyCode ? e.keyCode : e.charCode;
if ((input>=48 && input<=57) || (input==45))
{
if (input==45)
{
//focus the next input if there is one
while(inp.nextSibling)
{
var inp=inp.nextSibling;
if(inp.nodeType===1 && inp.tagName.toLowerCase()=="input")
{
inp.focus();
break;
}
}
return false
}
else
return true;
}
else
return false;
}
it just takes 10 seconds to ask google. you can't emulate a tab-keypress, but there are different workarounds (maybe you could use an array containing the id's of all you fields, save the index you're at and on pressing dash, focus index+1 in your array (+ setting the saved index onfocus of every text field to note if a user focuses a field by clicking it or really pressing tab))
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you. It does require jquery though.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want - (on the normal keys, I guess) instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use dash instead of plus
// Number 189 found through demo at
// https://api.jquery.com/event.which/
key: 189
});
// Matches all inputs with name "a[]" (needs some character escaping)
$('input[name=a\\[\\]]').plusAsTab();
You can try it out in the PlusAsTab demo, and check out the enter-as-tab demo. If you want to change to the - key, you can call JoelPurra.PlusAsTab.setOptions({key: 189}); from your javascript console.

Categories