How do I move focus to next input with jQuery? - javascript

I am using the autocomplete plugin with jQuery and it is working fine. However, in IE, when the user selects an item in the autocomplete, the focus does not then move to the next input field. Naturally it works in Firefox. The plugin doesn't have a built-in solution but does provide for "options". Is there a way I can force it to move to the next input field?

You can do something like this:
$("input").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
The other answers posted here may not work for you since they depend on the next input being the very next sibling element, which often isn't the case. This approach goes up to the form and searches for the next input type element.

JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters
HTML:
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
Javascript:
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});

What Sam meant was :
$('#myInput').focus(function(){
$(this).next('input').focus();
})

Try using something like:
var inputs = $(this).closest('form').find(':focusable');
inputs.eq(inputs.index(this) + 1).focus();

why not simply just give the input field where you want to jump to a id and do a simple focus
$("#newListField").focus();

Use eq to get to specific element.
Documentation about index
$("input").keyup(function () {
var index = $(this).index("input");
$("input").eq(index + 1).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />

you can use
$(document).on("keypress","input,select",function (e) {
e.preventDefault();
if (e.keyCode==13) {
$(':input).eq($(':input').index(this) + 1)').focus();
}
});

Could you post some of your HTML as an example?
In the mean-time, try this:
$('#myInput').result(function(){
$(this).next('input').focus();
})
That's untested, so it'll probably need some tweaking.

I just wrote a jQuery plugin that does what you are looking for (annoyed that that I couldn't find andy solution myself (tabStop -> http://plugins.jquery.com/tabstop/)

function nextFormInput() {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();
}

if you are using event.preventDefault() in your script then comment it out because IE doesn't likes it.

The easiest way is to remove it from the tab index all together:
$('#control').find('input[readonly]').each(function () {
$(this).attr('tabindex', '-1');
});
I already use this on a couple of forms.

Here is what worked in my case. Might be less performance intensive.
$('#myelement').siblings('input').first().focus();

var inputs = $('input, select, textarea').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});

onchange="$('select')[$('select').index(this)+1].focus()"
This may work if your next field is another select.

Related

HTML/Javascript Input type="text" - How to shows text different from value?

Actually i have a datalist:
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
This is used in an input:
<input type='text' name='dummy' autocomplete='off' list='modelsList' value=''/>
If i start typing Dummy2 and then i click on the dropdown list result the textbox shows 2. I need to find a way to have 2 as value but Dummy2 as text.
I cannot use a drop-down list (select tag)
Here, my solution as per you want check it out...
You can use input event for achieving such functionality,
HTML
<input type='text' id='dummy' list='modelsList'/>
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
Jquery
$("#dummy").on('input', function () {
var val = this.value;
if($('#modelsList option').filter(function(){
return this.value === val;
}).length) {
var option = $('#modelsList').find('option[value="' + val + '"]');
$(this).val(option.text());
}
});
also check DEMO of the above code.
The format for a text input in HTML5 is as follows:
<input type="text" name="name" value="Value" placeholder="Placeholder Text">
As a user types in their content, the value changes.
You may be getting confused with textarea:
<textarea name="name">Value</textarea>
If you want to put a textarea tag, you have to know that the value attribute is invalid, but perhaps if you want to use it instead of input, and the format is similar as you put:
<textarea name="name">contentHere</textarea>

Auto tab to next input field when fill 4 characters

What I am trying to do is, point to next tab when filling four characters. Each field should have 4 characters and once it is completed it should move to next input box.
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
Fiddle.
Your code works fine, however your input elements are set as type="number". Non-numeric content is ignored, so if you enter "abcd", for example, the input's value is empty (meaning a length of 0). If you enter "1234" on the other hand, the input's value is 1234.
If you want your code to fire when non-numeric content is entered, simply change each input's type to text.
<input class="inputs" type="text" maxlength="4" />
JSFiddle demo.
Note that I've also removed the duplicate class attribute from each of your elements in that example, too.
As krish has mentioned in the comments on your question, there is an issue with your code in that the last input element will continue to accept more than 4 characters. To fix this, put a check in place to ensure that there is a next('.inputs') element:
if (this.value.length == this.maxLength) {
var $next = $(this).next('.inputs');
if ($next.length)
$(this).next('.inputs').focus();
else
$(this).blur();
}
JSFiddle demo.
Perhaps you neglected to enclose your code in DOM ready. Jsfiddle encloses your code in $(window).load(function() { .....}) and that's why it's working. So on your own page use:
$(function() {
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
});
In the jsfiddle you can confirm that by selecting No wrap - in <head> and then click run. The code will not work. But if you use the above which is enclosed in DOM ready, it works.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<Script>
$(document).ready(function(){
$(".inputs").keyup(function () {
$this=$(this);
if ($this.val().length >=$this.data("maxlength")) {
if($this.val().length>$this.data("maxlength")){
$this.val($this.val().substring(0,4));
}
$this.next(".inputs").focus();
}
});
});
</Script>
</head>
<body>
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
</body>
Here is a improved Version for all who need this for some kind of splitted Informations like a serial key or something like that:
$(document).ready(function(){
$(".amazonInput").keydown(function (e) {
var code = e.which;
$this=$(this);
if ($this.val().length >=$this.data("maxlength") && code != 8) {
if($this.val().length>$this.data("maxlength")){
$this.val($this.val().substring(0,4));
}
$this.next(".amazonInput").focus();
}
if($this.val().length == 0 && code == 8) {
$this.prev(".amazonInput").focus();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My first issue with this has been that if tabbing through fields that are already filled, you have to select each field manually. I suggest this:
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').select();
}
});
The second issue's solution escapes me. Basically, in the same situation of having fields previously filled, if you type too quickly the events will fire as such: KeyDown KeyDown KeyUp KeyUp
What this causes, is to skip the next input.
For those Who Have tried the Accepted Answer, but Couldn't find solution like me
In your Layout Page or page header, just input ajax library link (Shown in below)
It worked on me, Hope It will help you as well.
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.inputs');
if ($next.length)
$(this).next('.inputs').focus();
else
$(this).blur();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
</body>

How to extract form element values in a loop?

I have a list of form elements that I want to loop over to get the values of, so if someone typed their name in the input i want their name, if they selected an option from a select box I want the not the numerical value but the string. All these values needs to be outputted as one string.
This is the loop i've created, I however have no idea how to go about this problem..
every form element has a name starting with credit_
if someone could point me in the right direction it would be much appreciated..
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
});
my html is quite simple.
<div class="comp-row">
<!-- a select -->
<!-- an input -->
</div>
This is part of the form, there are many other form fields but im only concerned with the ones within "comp-row" which Im manipulating a lot.
I ended up using:
$('.comp-row [name*="credit_"]:not([type=hidden])')
.each(function(index,elem)
{
console.log($(this).text() != '' ? $(this).find('option:selected').text().trim() : $(this).val());
});
}
Youre looking for the $('select[name*="credit_"]>option:selected') selector.
To read the text value for your , issue .text()
Combine this with if($('input[name*="credit_"]').text() != '') evaluation, combined something like this:
var theName = $('input[name*="credit_"]').text() != ''
? $('select[name*="credit_"]>option:selected').text()
: $('input[name*="credit_"]').text();
Depending on format you want you can use serialize() or serializeArray().
For example to obtain for whole form:
var data=$('#myForm').serialize()
For specific group of elements:
$('[name*=credit_]').serializeArray()
serialize() API docs
serializeArray() API docs
var result = '';
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
result += $(this).is("select") ? $(this).text() : $(this).val();
});
Iterate over all elements that match your criteria (name*=credit_). Check its type and put the value inside a variable.
HTML
<form>
<input type="text" name="credit_a" value="1" />
<input type="text" name="credit_b" value="2" />
<input type="text" name="credit_c" value="3" />
<select name="credit_d">
<option value="kk">kk</option>
<option value="jj" selected>jjjjj</option>
</select>
<input name="credit_e type="checkbox" checked value="imchecked" />
</form>
<form>
<input type="text" name="credit_a" value="55" />
<input type="text" name="credit_b" value="66" />
<input type="text" name="credit_c" value="77" />
<input type="text" name="credit_d" value="88" />
</form>
<p id="result"> </p>
javascript
$(function() {
var values = '';
$('form [name*=credit_]').each(function() {
var $this = $(this);
if($this[0].tagName == 'TEXTAREA') {
values += ' ' + $this.text();
}
else if ($this[0].tagName == 'SELECT') {
values += ' ' + $this.find(':selected').text();
}
else {
values += ' ' + $this.val();
}
});
$('#result').html(values);
});
jsfiddle: http://jsfiddle.net/5tgzr/2/

Form login button enabled after password field has focus

hello guys I have a login page with two inputs username and password and one button. I want to put a class on that button after password field has first character filled in. How can I do that , Thank's. If is possible to do that only with css will be awesome, or a small script to add a class on that button.
<form>
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last" value="login button" />
css
/*Normal State*/
.crbl{
margin-top:10px;
border:1px solid #555555;
border-radius:5px;
}
/*after password field has one character filled in state*/
.class{
???
}
fiddle:
http://jsfiddle.net/uGudk/16/
You can use toggleClass and keyup methods.
// caching the object for avoiding unnecessary DOM traversing.
var $login = $('.crbl');
$('#last').keyup(function(){
$login.toggleClass('className', this.value.length > 0);
});
http://jsfiddle.net/5eYN5/
Note that IDs must be unique.
You can do that using javascript. FIrst thing you need to put on password input the following event
Password <input type="text" name="last" id="last" onkeyup="myFunction(this);"/>
Then you define the javascript function:
function myFunction(element) {
if (element.value != '') {
document.getElementById('last').attr('class','password-1');
} else {
document.getElementById('last').attr('class','password-0');
}
}
You may try like this demo
jQuery(document).ready(function(){
jQuery('#last').keyup(function(event){
var password_length =jQuery("#last").val().length;
if(password_length >= 1){
jQuery("#last_button").addClass('someclass');
}
else
{
jQuery("#last_button").removeClass('someclass');
}
});
});
This is the best way to handle the entire input, with the "on()" Jquery method.
Use the very first parent
<form id="former">
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last_btn" value="login button" />
Then in Jquery
$("#former").on('keydown, keyup, keypress','#last',function(e){
var value = $(this).val();
if ( value.length > 0 ) {
$("#last_btn").addClass('class'):
}else{
$("#last_btn").removeClass('class');
}
});
With "on" method you can handle many event of the input as you can see...
make sure your ID is unique.. since you have two IDs with the same name in fiddle.. i changed the password id to 'password'...
use keyup() to check the key pressed.. and addClass() to add the class..
try this
$('#password').keyup(function(){
if($(this).val()==''){
$('#last').removeClass('newclassname'); //if empty remove the class
}else{
$('#last').addClass('newclassname'); // not not empty add
}
});
fiddle here
<script type="text/javascript">
$('#YourTextBoxId').keyup(function (e) {
if ($(this).val().length == 1) {
$(this).toggleClass("YourNewClassName");
}
else if ($(this).val().length == 0) {
$(this).toggleClass("YourOldClassName");
}
})
</script>
Test this:
http://jsfiddle.net/uGudk/33/
Please consider using unique id for all form elements, and use unique input name also.
$(document).ready(function(){
$("input[name=last]").keydown(function () {
if($(this).val().length > 0){
$(this).attr("class", "class");
//or change the submit button
$("input[type=submit]").attr("class", "class");
//or if you want to enable it if originally disbaled
$("input[type=submit]").removeAttr("disabled");
}
});
});

How to clear text field on focus of text field

I want to clear the text field when the user clicks on that
<input name="name" type="text" id="input1" size="30" maxlength="1000" value="Enter Postcode or Area" onfocus=="this.value=''" />
Unless you are doing something specific where you only want to clear onclick, I would suggest (as others have noted) to use the onfocus actions instead. This way if someone is using tab to navigate it will also clear the default text.
You can also use onblur to check if it's empty to bring it back:
<input type="text" value="Default text" name="yourName" onfocus="if(this.value == 'Default text') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Default text'; }">
To do this you will need to use a scripting language, probably javascript. Here an example
<input type='text' value'Some text' onclick='javascript: this.value = ""' />
Hope this helps.
Edit:
To meet what David is explain here is a second example in case that is what you are looking for
<script type='javascript'>
var clear = true;
function clear(obj)
{
if(clear)
{
obj.value = '';
clear = false;
}
}
</script>
<input type='text' value'Some text' onfocus='clear(this);' />
Using jQuery library:
<input id="clearme" value="Click me quick!" />
$('#clearme').focus(function() {
$(this).val('');
});
Or you can simply use the placeholder attribute
For example<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>
You can use <input ... onfocus="this.value='';"/>.
This way, the field will be cleared when it gains focus. However, if you only want to clear it when user clicks on it (i.e. not when the field gains focus with the keyboard for example), then use onclick instead of onfocus.
However, as pointed by David Dorward in a comment, this behavior may not be expected by the user. So be careful to set this feature on really specific fields (such as search field).
This is how I use it for a temperature converter/calculator - when the user types (keyup), the text input box calculates using the assigned function; when the user selects the other text input (there are only two inputs), the selected text input will clear.
HTML:
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" onfocus="this.value='';" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" onfocus="this.value='';"placeholder="Temperature (Fahrenheit)" />
</p>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}
try this ,it worked for me
add this into your input tag
<code>
onfocus="this.value='';"</code>
for example if your code is
<code>
<input type="text" value="Name" /></code>
use it like this
<code><input onfocus="this.value='';" type="text" value="Name" /></code>
function Clear (x) {if (x.cleared) {} else {x.value = ""; x.cleared = true}}
onfocus = "Clear (this)"
Add a following script to your js file:
var input1 = document.getElementById("input1")
input1.onfocus = function() {
if(input1.value == "Enter Postcode or Area") {
input1.value = "";
}
};
input1.onblur = function() {
if(input1.value == "") {
input1.value = "Enter Postcode or Area";
}
};

Categories