JavaScript onkeypress delayed trigger - javascript

I have an html input for an optional phone number, along with 2 radio inputs (Leave Message, Dont Leave Message):
<input type="text" class="input-medium phoneNum2" name="secondaryPhone" id="secondaryPhone" onkeypress="toggleRadio(this)" onblur="toggleRadio(this)" placeholder="703-555-1010" value="<cfoutput>#session.secondaryPhone#</cfoutput>" />
Notice I have two events running (deleting one of them yields the same issue, having both helps out, but I'd rather have only one event unless necessary).
The scenario here is: The second somebody starts typing into the input, it checks to see if one of the radio buttons is already checked. If not, default select yes. If for some reason they delete the phone number as they do not want to give it, both radio buttons should be de-selected (only the onblur works there). And if the "Don't Leave Message" is selected BEFORE the user starts typing, it should not default to yes.
Here is the JavaScript:
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
if (x.value.length > 0 && !z.checked) y.checked = true;
}
Now for the issue: The default option yes is only triggered when I type in 2 characters, instead of the desired 1 (almost like a delay in the code?). If I have "No" Selected before I start typing, it defaults to yes once I type in the 2 characters. Likewise for reverse, nothing is "de-selected" when there are 0 characters during the onkeypress event, only when the input loses focus during the onblur event.
Am I using the wrong events? Is there a logic flaw? There are no error messages, and no, I cannot use jQuery here, so please don't give me jQuery answers or the usual "Why no jQuery?" (I love jQuery I simply have reasons I cannot use it).
Edit: I also tried ordering the JavaScript like this, to no avail.
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length > 0 && !z.checked) y.checked = true;
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
}
Basically I want to know why the code is acting like there is a delay, and is there a way to fix it?

Try using onkeyup instead:
onkeyup="toggleRadio(this)"

Related

How can I delay moving to the next input field when the TAB button is pressed?

I was hoping I could get some help with a problem I've been having. I would like to set a small delay when the user presses the TAB button before the next input field found on the webpage is selected. The reason for this is that I am using AJAX to build an order form field, with expandable and collapsible tables that will be taking input from the user.
I have it set up using onfocusout to call a function that expands the table below the current table the user is in after they leave the last field, and would like the first input field to be auto selected right after. Everything works as should when the user exits the last field of a table by clicking out of it, but when tabbing out of it I believe there is a problem because there is not a field to be tabbed to until after it retrieves the next table to display using AJAX.
I can provide code if needed, but I think I'm missing something, rather than having a mistake somewhere. Help would be appreciated, and I'd be more than happy to clarify anything that is unclear. Thank you!
So, I've created a very basic example of how this can work. My example only accounts for inputs, but you can play with the code to do what you need.
Warning: Preventing natural browser behavior can be tricky so pay attention to other issues this could cause.
Here is a Fiddle showing how you can do this: https://jsfiddle.net/iamjpg/wme339h9/
document.onkeydown = TabExample;
// Basic function
function TabExample(evt) {
// Capture event
var evt = (evt) ? evt : ((event) ? event : null);
// Tab keycode constant
var tabKey = 9;
// If key is tab...
if (evt.keyCode == tabKey) {
// Prevent the next focus.
evt.preventDefault()
// Grab current focused element
var focusedElement = document.activeElement;
// Get array of inputs
var inputs = document.getElementsByTagName('input');
// Set delay of 2 seconds.
setTimeout(function() {
// Loop through inputs
for (i = 0; i < inputs.length; i++) {
// If current evaluated input is one with focus...
if (inputs[i] === document.activeElement) {
// Grab the next index...
var focus_input = i + 1;
// Assure it isn't undefined.
if (inputs[focus_input]) {
// Give new input focus.
inputs[focus_input].focus();
}
}
}
}, 2000)
}
}
Good luck!

Enable button (or any element) if at least one input has value

I'm need to enable a button (and perhaps other elements on the form in the near future) if at least one of the input element has values. I'm using BootstrapValidator as a main validation library since I'm using Twitter Bootstrap but have not idea, in the easy way, to achieve this. What I know is check each input one by one as for example:
if ($('.some_input').length > 0) { // then do actions }
But if I have many fields this solutions seems to be tedious and not very practical, also I'll need to trigger in some many events as for example: keypress, keyup, keydown, blur and maybe others too (not clear at all).
Right now the form is pretty simple as image shows below and the my solution should works but the form will grow up fast and in the near future so I leave it behind and I'm looking for another solution.
Here the button "Buscar" (it's enabled on the img but doesn't care about this I miss to disabled when I took the screenshoot) should be enabled only if any of the input on the form (Codigo de la Norma, Año de Publicacion, Palabra o Termino que contiene la Norma) has values and possibly a choice marked on the select below has a value different from the default (can be any as for example --Pick one-- with value=0) in a simple words: any input has at least 3 characters minimmum and choice in the SELECT should be different from the default one, how can I do that?
$(function() {
$(':text').on('input', function() {
if( $(':text').filter(function() { return !!this.value; }).length > 0 ) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<button disabled="disabled">Submit</button>
</form>
Update
To expand this so it works with other form elements (excluding radios and checks) you can change :text to :input. And the code can be shortened to the following:
$(function() {
$(':input').on('input', function() {
var completed = $(':input').filter(function() { return !!this.value; }).length > 0;
$('button').prop('disabled', !completed);
});
});
Each input element has an event called change attached to it. I would add a function to run whenever this is done.
If you really want to run code whenever even one letter is added to a field, you can instead use the event known as input (be sure to check the performance of any code like this though, as it will be triggered alot!)
Although, there is much less browser support for the input event than the change one.
$('input.some_input').on('change', function() {
if ($(this).val().length > 0) {
alert('woot! text!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='some_input' value='test' />

How can I set the focus to the next field (based on tabindex) using JavaScript? [duplicate]

In jQuery, how can I trigger the behavior of a user tabbing to the next input field?
I've tried this:
var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);
But triggering the event doesn't move the cursor to the next field.
I suppose I could move the cursor manually using focus(), but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.
Any ideas?
Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
$.fn.focusNextInputField = function() {
return this.each(function() {
var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
});
};
The use is as follows:
$( 'current_field_selector' ).focusNextInputField();
See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup event, and check the entered number of characters.
The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus event on the element with that index.
There's a JQuery plugin available:
http://www.mathachew.com/sandbox/jquery-autotab/
Have you tried using
$("input").trigger( 'keypress', e );
as a solution?
I find sometimes being explicit is best.
If that doesn't work possibly even
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );.
Hope this helps.

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

Preventing focus on next form element after showing alert using JQuery

I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?
$('input.IosOverrideTextBox').bind({
blur: function(e) {
var val = $(this).val();
if (val.length == 0) return;
var pval = parseTicks(val);
if (isNaN(pval) || pval == 0.0) {
alert("Invalid override: " + val);
return false;
}
},
focus: function() {
$(this).select();
}
});
I don't like forced focus, but can't you just focus after the blur takes place?
element.focus();
If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).
But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.
You can do this with the validation plugin by default.
focusInvalid default: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Then you'd only need to have the focus event handler do your select and let the plugin handle validation.

Categories

Resources