Jquery select NEXT text field on Enter Key Press - javascript

I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.

I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one

You should use:
$(this).next('input').focus();

try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...

Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.

Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}

<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>

This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});

Related

html show hide password not working mobile [duplicate]

How can I do this through the tag itself?
Change type from text to password
<input type='text' name='pass' />
Is it possible to insert JavaScript code inside the input tag itself to change type='text' to type='password'?
Try:
<input id="hybrid" type="text" name="password" />
<script type="text/javascript">
document.getElementById('hybrid').type = 'password';
</script>
Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).
You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.
I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84
To work in Internet Explorer:
dynamically create a new element
copy the properties of the old element into the new element
set the type of the new element to the new type
replace the old element with the new element
The function below accomplishes the above tasks for you:
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>
Yes, you can even change it by triggering an event
<input type='text' name='pass' onclick="(this.type='password')" />
<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the <input> tag to trigger the appropriate JavaScript code. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" ||
document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
let btn = document.querySelector('#btn');
let input = document.querySelector('#username');
btn.addEventListener('click',()=> {
if ( input.type === "password") {
input.type = "text"
} else {
input.type = "password"
}
})
<input type="password" id="username" >
<button id="btn">change Attr</button>
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that the input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
This is a simple toggle with jQuery. It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.
function showPassword() {
let password = $(".password");
if (password[0].type == "password") {
password[0].type = "";
}
else {
password[0].type = "password";
}
}
$(".show-pass").click(function (e) {
e.preventDefault();
var type = $("#signupform-password").attr('type');
switch (type) {
case 'password':
{
$("#signupform-password").attr('type', 'text');
return;
}
case 'text':
{
$("#signupform-password").attr('type', 'password');
return;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="password" class="show-pass">
This is not supported by some browsers (Internet Explorer if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
You can try this:
const myTimeout = setTimeout(show, 5000);
function show() {
document.getElementById('pass').type = "text";
}
clearTimeout(myTimeout);
//html
<input type="password" id="password_input">
<i onclick="passwordDisplay()" class="ti-eye"></i>
//js
const input = document.getElementById("password_input")
function passwordDisplay() {
if (input.attributes["type"].value == "text")
input.attributes["type"].value = "password"
else
input.attributes["type"].value = "text"
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
document.getElementById("password-field".focus();
}
</script>
</head>
<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />
</body>
</html>

how to display the array of values for the single field using jquery?

Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';

call a JS function inside an event method

I hope I'm not repeating a question but I've searched around and couldnt find help so I thought I should ask directly, I'm still a beginner and this is an assignment for my class so please be as thorough as possible
I'm trying to create a form where as the user clicks on another field, it checks if the input he put in the first one is as required by the website, without having to click enter or a submit button.
this is the HTML file.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function(){
$("div.ID").focusin(function(){
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").focusout(function(){
$(this).css("background-color", "#FFFFFF");
userid_validation(userid,5,12);
});
});
</script>
</head>
<body>
<div class="ID" >
User ID: <input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password: <input type="text" name="psw" size="12" />
</div>
</body>
</html>
and this is the JS file
function userid_validation(userid,mx,my)
{
var uid_len = userid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
//uid.focus();
return false;
}
return true;
}
I'm most probably doing something completely wrong but I don't know what. thanks in advance !
You need to apply focusin and foucsout on input elements. Currently you have applied it on div. Also you have code error on calling following function,
userid_validation(userid, 5, 12); // userid not defined.
Please check if this works.
function userid_validation(userid, min, max) {
var uid_len = userid.length;
if (uid_len == 0 || uid_len > max || uid_len < min) {
alert("User Id should not be empty / length be between " + min+ " to " + max);
//uid.focus();
return false;
}
return true;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function() {
$("div.ID").find('input').focusin(function() {
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").find('input').focusout(function() {
$(this).css("background-color", "#FFFFFF");
userid_validation($(this).val(), 5, 12);
});
});
</script>
</head>
<body>
<div class="ID">
User ID:
<input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password:
<input type="text" name="psw" size="12" />
</div>
</body>
</html>

JQuery - filter labels that start with typed in text

i have this list of cities(checkbox and label) and an input field:
<input class="search-filter" type="text"/>
<form autocomplete="off" id="city-search-form" name="city-search-form" action="" method="">
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
<input id="city-id-2" class="css-checkbox" type="checkbox" />
<label for="city-id-2" name="" class="css-label">bce</label>
<input id="city-id-3" class="css-checkbox" type="checkbox" />
<label for="city-id-3" name="" class="css-label">cde</label>
<input id="city-id-4" class="css-checkbox" type="checkbox" />
<label for="city-id-4" name="" class="css-label">rgp</label>
</div>
</form>
i am using this jquery code to filter the checkboxes + labels by the words i type in, but the code is not working. How can i filter and show only the labels that start with typed words.
function listFilter(list) {
var input = $('.search-filter');
$(input)
.change( function () {
var filter = input.val();
$('.css-label').filter(function(filter) {
if($('.css-label').text().search(filter) == 0){
.....hide();
}
else {
.......show();
}
});
})
.keyup(function () {
input.change();
.....
}
});
}
$(function () {
listFilter($("#list"));
});
}($));
Try
function listFilter(list, input) {
var $lbs = list.find('.css-label');
function filter(){
var regex = new RegExp('\\b' + this.value);
var $els = $lbs.filter(function(){
return regex.test($(this).text());
});
$lbs.not($els).hide().prev().hide();
$els.show().prev().show();
};
input.keyup(filter).change(filter)
}
jQuery(function($){
listFilter($('#list'), $('.search-filter'))
})
Demo: Fiddle
You can use :contains() selector for filtering:
var input = $('.search-filter');
input.change( function () {
var filter = input.val();
if(filter.length == 0) { // show all if filter is empty
$('.css-label').each(function() {
$(this).show();
$(this).prev().show();
});
return;
}
// hide all labels with checkboxes
$('.css-label').each(function() {
$(this).hide();
$(this).prev().hide();
});
// show only matched
$('.css-label:contains("'+filter+'")').each(function() {
$(this).show();
$(this).prev().show();
});
}).keyup(function() {
$(this).change();
});
jsfiddle
Too late to be accepted as correct but here is an attempt that I was working on before my job got in the way. Thought I may as well post it.
It is case insensitive and supports multiple words (thanks to Arun P Johny for that).
demo
$('.search-filter').keyup(function (e) {
var text = $(this).val();
var $elems = $('.css-label, .css-checkbox');
if (text.length < 1) {
$elems.show();
}
else{
$elems.hide();
var sel = $('label').filter(function () {
return $(this).text().match("\\b", "i" + text)
}).attr('for');
$('#'+sel + ',[for=' + sel + ']').show();
}
});
i have a code below to get the label name
<!DOCTYPE html>
<html>
<head>
<SCRIPT src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</SCRIPT>
<SCRIPT>
$(document).ready(function(){
alert($(".css-label").text());
});
</SCRIPT>
</head>
<body>
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
</div>
</body>
</html>
hope this will help you

javascript function not calling possibly due to scope issue

I am looking to call my clear() JS function to clear the text values in some input fields on my webpage, but for some reason, the function doesn't appear to be called correctly. I believe this may be a scope issue, but I'm not sure.
Here is my markup, script and styling kept together for ease-of-use currently, but will be mended once scripting is finalized:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
}
function clear()
{
document.getElementById('variablea').value = "";
document.getElementById('variableb').value = "";
document.getElementById('variablec').value = "";
}
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button" onClick="calculateQuad()">
<input id="erase" value="Clear" type="button" onClick="clear()">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
You must rename the 'clear' method. Try naming it 'clearFields' or something. (;
Also, if you only want to reset the form fields you can also do this:
onClick="this.form.reset()"
You can avoid the issue with function naming entirely by using:
document.getElementById("calculate").onclick = function () {
...
};
document.getElementById("erase").onclick = function () {
...
};
This is actually a preferred method of adding event handlers by web developers because it avoids cluttering the HTML code with inline snippets of JavaScript while retaining cross-browser compatibility.

Categories