How would I focus on a input with jQuery - javascript

I'm trying to focus on a input using jQuery. I can easily do this by using the id of the input tag, however this is set to the id from a database field, and is ordered in a different way. This makes this not work as well as i want when using to focus on. What I want to be able to do is use the HTML5 data attribute to focus onto so the following would work:
<input class="navigable" type="text" data-id="1" ID="123" data-number="1" maxsize="1"> I want to be able to focus on this using jQuery. Currently I have:
$('.navigable').keyup(function() {
var self = $(this);
var next = $('#txt'+(self.data('number')+1));
if(next.length > 0 && self.val().length == self.attr('size')) {
next.focus();
}
My HTML tag has to be like this:
<input type="text" class="navigable" id="txt1" data-number="1" maxsize="1">
Thanks in advance.

You have typo in your code. You forgot to close if condition }. And self.attr('size') will return undefined. Because you dont have any attribute named size in your input. So replace self.attr('size') with self.data('number').
Try this:
$('.navigable').keyup(function() {
var self = $(this);
var next = $('#txt'+(self.data('number')+1));
console.log(next);
if(next.length > 0 && self.val().length == self.data('number')) {
next.focus();
}
});
DEMO

Try
Attribute Equals Selector [name="value"]
$('input.navigable[data-number="1"]').focus();
$('.navigable').keyup(function () {
var self = $(this);
var next = $('input.navigable[data-number="' + (self.data('number')+1) + '"]');
if (next.length > 0 && self.val().length == self.data('number')) {
next.focus();
}
});

You could use autofocus attribute on your input element, which is plain HTML5.
$('input.navigable[data-number="' + num +'"]').prop('autofocus', true);

Related

Mask if more then x characters

I am using a masking plugin (http://digitalbush.com/projects/masked-input-plugin/) it works, but I am trying to get it to only work once there are 5+ characters in the textbox. Whenever I hit the 6th character, it clears out the textbox and won't accept input anymore.
JS:
<script>
function convert(){
if (l.length > 5){
$("#q").mask('(999) 999-9999');
}
}
</script>
HTML:
<form action="search.php" method="GET">
<input type="tel" class="form-control" name="q" id="q" placeholder="Phone/Order Number" onkeyup="convert()"><br>
<button type="submit" class="btn btn-default">Search</button>
</form>
if someone could please help me, that would be great. :D
It clears out the textbox because when you apply a mask, the plugin clears the input. You can get around this by passing the autoclear option and set it to false. It would also keep attempting to apply the mask, so you'd have to remove the event listener. So ditch the inline event handler, that's a bad way to do event handlers anyway :-)
Something like this would work:
$('#q').on('keyup', function() {
var $el = $(this);
var val = $el.val();
if (val.length > 5){
$el.mask('(999) 999-9999', {
autoclear: false,
placeholder: ''
});
}
});
Note that I also set the placeholder to an empty string, otherwise when the mask is applied the cursor will be set to the end of the mask placeholder and you'd have to move the caret back a few spaces.
This will detect a Backspace and revert it from phone number mask to a plain mask
$('#q').on('keyup', function(event) {
var $el = $(this);
var val = $el.val();
if (val.length > 5){
$el.mask('(999) 999-9999', {autoclear: false,placeholder: ''});
}
if (event.keyCode == 8){
$el.mask('999999', {autoclear: false,placeholder: ''});
}
});

How to move focus on next field when enter is pressed?

Can you please tell me how to move focus on to the next field when the enter key is press? I use the dform plugin (which converts JSON to a form).
I Googled it, but this not working. Why doesn't my focus move on to the next field?
JSFiddle: http://jsfiddle.net/5WkVW/1/
$(document).keypress(function(e) {
if(e.which == 13) {
// Do something here if the popup is open
alert("dd")
var index = $('.ui-dform-text').index(this) + 1;
$('.ui-dform-text').eq(index).focus();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form id="testSuiteConfigurationform" name="testSuiteConfigurationform" method="post" class="ui-dform-form" novalidate="novalidate">
<label class="ui-dform-label">
<h3>Configuration Parameters</h3>
</label>
<div class="ui-dform-div inputDiv">
<fieldset class="ui-dform-fieldset">
<input type="text" id="totalRetryCount" name="totalRetryCount" tabindex="1" onblur="validateElement('Configuration', 'testSuiteConfigurationform','totalRetryCount')" class="ui-dform-text valid">
<legend class="ui-dform-legend">Total Retry Count</legend>
<label for="totalRetryCount" class="checked">✔</label>
</fieldset>
<fieldset class="ui-dform-fieldset">
<input type="text" id="totalRepeatCount" name="totalRepeatCount" tabindex="2" onblur="validateElement('Configuration', 'testSuiteConfigurationform','totalRepeatCount')" class="ui-dform-text">
<legend class="ui-dform-legend">Total Repeat Count</legend>
</fieldset>
<fieldset class="ui-dform-fieldset">
<select id="summaryReportRequired" name="summaryReportRequired" tabindex="3" onblur="validateElement('Configuration', 'testSuiteConfigurationform','summaryReportRequired')" class="ui-dform-select">
<option class="ui-dform-option" value="true">true</option>
<option class="ui-dform-option" value="false">false</option>
</select>
<legend class="ui-dform-legend">Summary Report Required</legend>
</fieldset>
<fieldset class="ui-dform-fieldset">
<select id="postConditionExecution" name="postConditionExecution" tabindex="4" onblur="validateElement('Configuration', 'testSuiteConfigurationform','postConditionExecution')" class="ui-dform-select">
<option class="ui-dform-option" value="ALWAYS">ALWAYS</option>
<option class="ui-dform-option" value="ON_SUCCESS">ON_SUCCESS</option>
</select>
<legend class="ui-dform-legend">Post Condition Execution</legend>
</fieldset>
</div>
</form>
*Note (from comments): It also needs to work on pages that do not have tabindex values set
It fails because this is the document in your code.
You want to use the index of the currently focused item (document.activeElement), or if you use delegated events you can make sure this is the current item.
This final version works whether there are tabindexes or not. It also wraps around:
JSFiddle 1: http://jsfiddle.net/TrueBlueAussie/5WkVW/11/
JSFiddle 2: http://jsfiddle.net/TrueBlueAussie/5WkVW/12/
They both use a custom jQuery selector that I add called :focusable to select all focusable element (including links):
// register jQuery extension
jQuery.extend(jQuery.expr[':'], {
focusable: function (el, index, selector) {
return $(el).is('a, button, :input, [tabindex]');
}
});
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
// Get all focusable elements on the page
var $canfocus = $(':focusable');
var index = $canfocus.index(this) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
You can use the same custom selector in the event handler if you like. Then it will even work on anchor links (if you change the event to keydown instead of keypress):
e.g.
$(document).on('keydown', ':focusable', function (e) {
Example with link: http://jsfiddle.net/5WkVW/15/
This also uses a delegated on, listening for the keydown event on the document. It then applies the jQuery selector, it then applies the function to any matching element that caused the event. This is much more efficient as it only applies the selector at event time (rather than apply multiple event handler to each DOM matching element).
Old versions below:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5WkVW/3/
$(document).keypress(function(e) {
if(e.which == 13) {
// Do something here if the popup is open
//alert("dd")
var index = $('.ui-dform-text').index(document.activeElement) + 1;
$('.ui-dform-text').eq(index).focus();
}
});
*Note: alerts can interfere with focus, so use console.log for output like that and view in most browser's debug window (like Chrome's F12 debugging tools).
Update: http://jsfiddle.net/TrueBlueAussie/5WkVW/4/
This one wraps back to the first item from the last and also works on selects (the default behavior is blocked, so you can only use space to open or up/down to select options.
$('input,select').on('keypress', function (e) {
if (e.which == 13) {
e.preventDefault();
var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']');
console.log($next.length);
if (!$next.length) {
$next = $('[tabIndex=1]');
}
$next.focus();
}
});
Requested "document" version: http://jsfiddle.net/TrueBlueAussie/5WkVW/5/
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']');
console.log($next.length);
if (!$next.length) {
$next = $('[tabIndex=1]');
}
$next.focus();
}
});
I've created a non-jQuery version. So only pure Javascript;
https://jsfiddle.net/mm0uctuv/2/
Javascript:
var inputs = document.querySelectorAll("input,select");
for (var i = 0 ; i < inputs.length; i++) {
inputs[i].addEventListener("keypress", function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = document.querySelectorAll('[tabIndex="' + (this.tabIndex + 1) + '"]');
if (nextInput.length === 0) {
nextInput = document.querySelectorAll('[tabIndex="1"]');
}
nextInput[0].focus();
}
})
}
HTML:
<form>
Field 1: <input type="text" tabindex="1"><br>
Field 3: <input type="text" tabindex="3"><br>
Field 2: <input type="text" tabindex="2">
</form>
On the top-level div, add onKeyDown={this.onKeyDown.bind(this)} and add the following method (ES6) to the same class as the div:
onKeyDown(event) {
if (event.keyCode === 13) {
event.preventDefault()
const inputs =
Array.prototype.slice.call(document.querySelectorAll("input"))
const index =
(inputs.indexOf(document.activeElement) + 1) % inputs.length
const input = inputs[index]
input.focus()
input.select()
}
}
The following code should do it; it uses the tabIndex property. Let us know if that's is not acceptable:
$(function() {
$('input').on('keypress', function(e) {
e.which !== 13 || $('[tabIndex=' + (+this.tabIndex + 1) + ']')[0].focus();
});
});
The drop down already has enter key slated for opening the drop down.
JS FIDDLE DEMO
To be able to do something before moving to the next form element, you can use the following version:
$(function() {
$(document).on('keypress', function(e) {
var that = document.activeElement;
if( e.which == 13 ) {
e.preventDefault();
alert( "dd" );
$('[tabIndex=' + (+that.tabIndex + 1) + ']')[0].focus();
}
});
});
DEMO
Try the following JavaScript code that I modified from your fiddle. The default behavior of the select elements will be to expand on the keypress. The plus sign at the beginning of +$(this).attr("tabindex")
Converts the text attribute value to int.
$(".ui-dform-text").keypress(function(e) {
if(e.which == 13) {
// Do something here if the popup is open
alert($(this).attr("tabindex"));
var index = +$(this).attr("tabindex") + 1;
$("[tabindex='" + index +"']").focus();
}
});
This is mostly a joke but here is a Vanilla JS version using the newest APIs as long as you have a modern browser, it should be bullet proof
Here's what's happening:
Select Elements, inputs, etc... (excluding disabled, hidden, etc...)
Using the spread syntax, convert array (NodeList) to an object (here it's NodeObject)
Loop through the Objects aka Elements aka Nodes
Each iteration will pass the current element (Node) and the next element (NextNode) to an arrow function.
Continue if NextNode is an element
Then add a keypress event to the current element
Inside the event:
Continue only if the enter key was pressed (using e.key NOT e.keyCode or e.which -- which are deprecated)
Stop the Form from being submitted
Focus the next element
If we can, Select the text in the next node
And just like that you have some really unreadable code that is mostly parenthesis and arrow functions :)
// NodeList of applicable inputs, select, button
let NodesArray = document.querySelectorAll(`
#form input:not([disabled])[type]:not([type=\"hidden\"]),
#form select:not([disabled]),
#form button:not([disabled])[type=\"submit\"]
`);
// Spread the array to an object so we can load the next node without
// keeping track of indexes (barf)
(NodesObject => {
// Node and NextNode are Elements.
// You can update and get data if you want
Object.keys(NodesObject).forEach(i => (({ Node, NextNode }) => {
// Break if we dont have a NextNode
if (NextNode === false) return;
Node.addEventListener('keypress', KeyboardEvent => {
// Only continue if event.key was "Enter"
if (KeyboardEvent.key !== "Enter") return;
// Dont submit, thx
KeyboardEvent.preventDefault();
// Do the thing
NextNode.focus();
// Not all elements have a select method
if (typeof NextNode.select === 'function') NextNode.select();
});
})({
Node: NodesObject[i],
NextNode: NodesObject[(parseInt(i) + 1)] ?? false
}));
})({ ...NodesArray });
it looks the same, but I offer something simple, maybe helpful, and easy to remember, and this is what I use
html
<input placeholder="nama">
<input placeholder="email">
<input placeholder="password">
<button>MASUK<button>
js
$('INPUT').keydown( e => e.which === 13?$(e.target).next().focus():"");
// This will work; add this code in your on ready function and define your parent element which includes child elements to be focused.
const mainDiv = document.getElementById(`auto-focuser`); //here your parent element you need to focus
const keyDownEvent = (event) => {
if (event.key === "Enter") {
if (event.target.tagName === "TEXTAREA" && (event.target.innerHTML !== "" && event.target.innerHTML.substr(-1) !== "\n"))
return;
if (event.target.attributes.tabindex) {
const nextElm = mainDiv.querySelectorAll(`[tabindex='${parseInt(event.target.attributes.tabindex.value) + 1}']`).item(0)
if (nextElm) {
nextElm.focus()
if (nextElm.tagName === "INPUT" || nextElm.tagName === "TEXTAREA") {
nextElm.select()
nextElm.selectionStart = nextElm.selectionEnd = nextElm.value.length;
}
event.preventDefault()
}
}
}
}
mainDiv?.addEventListener('keydown', keyDownEvent);
1.first = you should put 'textbox' on your class name in input
2.second = put specific id for each input
then write this code for select that element and go to next element.
I select each element by each id and put next() function on keypress of every input.
function next(event,elem){
if ( event.keyCode == 13)
{
var list = document.getElementsByClassName("textbox");
for (var i=0 ; i<list.length ; i++)
{
if (elem.id == list[i].id)
{
var index = i + 1;
list[index].focus();
}
}
}
}
event args use for keybord press//
elem args use for element that we press eneter

If a specific value is inputed into an input box, display a message using javascript

I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);

How to match children innerText with user input using jQuery

I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});

Using jQuery to display input TITLE as VALUE (jsfiddle included)

I am trying to come up with a simple jquery input watermark function. Basically, if the input field has no value, display it's title.
I have come up with the jquery necessary to assign the input's value as it's title, but it does not display on the page as if it was a value that was hand-coded into the form.
How can I get this to display the value when the page loads in the input field for the user to see?
Here's the fiddle: http://jsfiddle.net/mQ3sX/2/
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
value = title;
}
$(".result").text(value);
// You can see I can get something else to display the value, but it does
// not display in the actual input field.
});
});
Instead of writing your own, have you considered using a ready-bake version? It's not exactly what you asked for, but these have additional functionality you might like (for instance, behaving like a normal placeholder that auto-hides the placeholder when you start typing).
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
http://archive.plugins.jquery.com/project/input-placeholder
Use the below line of code. You need to specify the input element, and update its value. Since your input field has a class called '.wmk', I am using the below code. You can use "id" and use "#" instead of ".". Read more about selectors at http://api.jquery.com/category/selectors/
$(".wmk").val(value);
Updated jsfiddle http://jsfiddle.net/bhatlx/mQ3sX/9/
Update: since you are using 'each' on '.wmk', you can use
$(this).val(value)
I think what you want is this:
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
$(this).val(title);
}
$(".result").text(value);
});
});
May be you want something like below,
DEMO
$(document).ready(function() {
$(".wmk").each (function () {
if (this.value == '') this.value = this.title;
});
$(".wmk").focus(
function () {
if (this.value == this.title) this.value = '';
}
).blur(
function () {
if (this.value == '') this.value = this.title;
}
);
}); // end doc ready

Categories