what to write after console.log('successful') so that i enter into next input field using id?
<script>
function invokeFunc() {
addEventListener('keydown', function(evt) {
var whichKey = checkKey(evt);
if (whichKey == 13) {
console.log('successful');
}
});
}
function checkKey(evt) {
console.log(evt.which);
return evt.which;
}
</script>
That should work:
if (whichKey == 13) {
console.log('successful');
evt.preventDefault(); // if it's inside <form> tag, you don't want to submit it
document.getElementById('nextInputID').focus();
}
my method will work if the input field is next each other like this
<input type="text">
<input type="text">
you can improve this by figuring out how to get the next input field when keycode is 13
in my case i use nextelementsibling and check if its an input (*you can add or logical || nextEl.nodeName === 'SELECT')
if nextElement is form field then focus() on it if not you done
document.querySelectorAll('input').forEach( el => {
console.log(el)
el.addEventListener('keydown', e => {
console.log(e.keyCode);
if(e.keyCode === 13) {
let nextEl = el.nextElementSibling;
console.log(nextEl)
if(nextEl.nodeName === 'INPUT') {
nextEl.focus();
}else {
alert('done');
}
}
})
})
Sorry if this question has already been asked, I am trying to create an app where the user scans a bar code and the data is then shown on the screen. I don't want to use textbox's because I don't want the data to be editable.
So far I've managed to get the enter key which is automatically sent at the end of the barcode but can't seem to get the keys pressed before, any help would be massively appreciated!
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + e.which();
}
});
Just to clarify what I want to do is show an alert box with the keys pressed before enter! For example : A B C D ENTER would show an alert("ABCD")
Thanks!
UPDATE
So got my code to work but I'm getting "undefinedTHEKEYSPRESEDHERE" as the return:
var counter = 0;
var item = [];
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item[counter]);
counter++;
}else{
item[counter] = item[counter] + String.fromCharCode(e.which);
}
});
Obviously this isn't clear enough, so I've outlined my problem below:
What I'm getting from alert(item[counter]);:
undefinedKEYS
What I want from alert(item[counter]);:
KEYS
So from undefinedKEYS to just KEYS I need to remove the text "undefined".
Clear enough?
Change e.which() to String.fromCharCode(e.which).
http://jsfiddle.net/8msksn3a/
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which);
}
});
Not that I recommend this way of checking for previous results, but you are basically resetting item to "" inside the keypress event. Set it once outside the event.
which is a property, not a method:
Convert from ASCII to string char with string.fromCharCode (A google search would have given you that in two seconds).
Use (e.which || e.keyCode) to ensure you get the keycode on all browsers.
e.g.
var item = "";
$(document).keypress(function(e) {
if((e.which || e.keyCode) == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which || e.keyCode);
}
});
Copy paste to your console and run:
var keys = [];
$(document).keypress(function(e) {
var keyChar;
if(e.which == 13) {
console.log( keys.join('') );
keys.length = 0;
}
else{
keyChar = String.fromCharCode(e.which);
if( keyChar )
keys.push( keyChar );
}
});
This technique will not show keys which does not have a textual character assigned to them (like the F1-F12 keys for example)
I need to deny initial spaces on my input (which is not in a form), I have code like this:
<input id="customer-name" class="required no-spaces" minlength="3" />
And this is my javascript function:
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
return false;
}
});
But this doesn't allow spaces in any part of the input. How to do it just before any text?
Edit: The real is that I'm doing an autocomplete with the input and, If i allow initial spaces it will return all data.
Verify if the string is empty beforehand.
$(".no-spaces").on('keypress', function(e) {
if ($(this).val() == "" && e.which == 32) {
return false;
}
});
Also, check this in order to prevent the case where the user selects the entire text and then presses space and this to check if the cursor is indeed at the beggining of the input (Thanks to Barmar for mentioning this specific case)
Just simply check there is another character on textbox.
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32 && ($this).val() == '') {
return false;
}
});
Edit
I hope it might be work.
$(".no-spaces").on('keypress', function(e) {
$(this).val(function(i, v) {
if (v[0] == ' ') {
return v.slice(1, v.length);
};
return v;
});
});
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
$(this).val($(this).val().replace(/^\W*/, ''));
}
});
This works for me.
$(".no-spaces").on('keypress', function(e) {
var val = $(this).val();
val_ltrim = ltrim(val);
$(this).val(val_ltrim);
});
Greetings.
I'm calling a function (below) that will perform an action if the user presses the delete button. It is working fine but I need to to only do it on the page and not when a user is typing (inside an input or inside a textarea).
$(window).keydown(function (evt) {
if (evt.which == 46) { // delete
goDoSomething();
}
});
Any ideas how I can amend the above to not fire if the user is in an input or textarea?
Thanks in advance,
Dave
check evt.target's type:
$(window).keydown(function (evt) {
if (evt.target.tagName.toLowerCase() !== 'input' &&
evt.target.tagName.toLowerCase() !== 'textarea' && evt.which == 46) { // delete
goDoSomething();
}
});
You could have a global variable and set it to something when a textbox is focussed on and reset it on blur. Something like this:
var textboxSelected = false;
$(":input").focus(function () {
textboxSelected = true;
});
$(":input").blur(function () {
textboxSelected = false;
});
Then in your onKeyDown event check whether the variable is set to false before carrying out the rest of the functionality:
$(window).keydown(function (evt) {
if (evt.which == 46 && textboxSelected == false) {
goDoSomething();
}
});
try sometihing like this:
$(window).keydown(function (evt) {
if(evt.target != $('input') && evt.target != $('textarea')){
if (evt.which == 46) { // delete
goDoSomething();
}
}
});
I'm using ASP.NET 2.0 with a Master Page, and I was wondering if anyone knew of a way to detect when the fields within a certain <div> or fieldset have been changed (e.g., marked 'IsDirty')?
You could bind the Change event for all inputs and flag a variable as true. Like this.
var somethingChanged = false;
$(document).ready(function() {
$('input').change(function() {
somethingChanged = true;
});
});
But, keep in mind that if the user changes something, then changes back to the original values, it will still be flagged as changed.
UPDATE: For a specific div or fieldset. Just use the id for the given fieldset or div. Example:
var somethingChanged = false;
$(document).ready(function() {
$('#myDiv input').change(function() {
somethingChanged = true;
});
});
Quick (but very dirty) solution
This is quick, but it won't take care of ctrl+z or cmd+z and it will give you a false positive when pressing shift, ctrl or the tab key:
$('#my-form').on('change keyup paste', ':input', function(e) {
// The form has been changed. Your code here.
});
Test it with this fiddle.
Quick (less dirty) solution
This will prevent false positives for shift, ctrl or the tab key, but it won't handle ctrl+z or cmd+z:
$('#my-form').on('change keyup paste', ':input', function(e) {
var keycode = e.which;
if (e.type === 'paste' || e.type === 'change' || (
(keycode === 46 || keycode === 8) || // delete & backspace
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223))) { // [\]' (in order))
// The form has been changed. Your code here.
}
});
Test it with this fiddle.
A complete solution
If you want to handle all the cases, you should use:
// init the form when the document is ready or when the form is populated after an ajax call
$(document).ready(function() {
$('#my-form').find(':input').each(function(index, value) {
$(this).data('val', $(this).val());
});
})
$('#my-form').on('change paste', ':input', function(e) {
$(this).data('val', $(this).val());
// The form has been changed. Your code here.
});
$('#my-form').on('keyup', ':input', function(e) {
if ($(this).val() != $(this).data('val')) {
$(this).data('val', $(this).val());
// The form has been changed. Your code here.
}
});
Test it with this fiddle.
A simple and elegant solution (it detects form elements changes in real time):
var formChanged = false;
$('#my-div form').on('keyup change paste', 'input, select, textarea', function(){
formChanged = true;
});
For a form you could serialize the contents on load then compare serialization at a later time, e.g.:
$(function(){
var initdata=$('form').serialize();
$('form').submit(function(e){
e.preventDefault();
var nowdata=$('form').serialize();
if(initdata==nowdata) console.log('nothing changed'); else console.log('something changed');
// save
initdata=nowdata;
$.post('settings.php',nowdata).done(function(){
console.log('saved');
});
});
});
Note this requires form elements to have a name attribute.
Just to clarify because the question is "within a certain fieldset/div":
var somethingChanged = false;
$(document).ready(function() {
$('fieldset > input').change(function() {
somethingChanged = true;
});
});
or
var somethingChanged = false;
$(document).ready(function() {
$('div > input').change(function() {
somethingChanged = true;
});
});
You can give the fieldset or div an ID and bind the change event to it ... the event should propagate from the inner children.
var somethingChanged = false;
$('#fieldset_id').change(function(e)
{
// e.target is the element which triggered the event
// console.log(e.target);
somethingChanged = true;
});
Additionally if you wanted to have a single event listening function you could put the change event on the form and then check which fieldset changed:
$('#form_id').change(function(e)
{
var changedFieldset = $(e.target).parents('fieldset');
// do stuff
});
I came up with this piece of code in CoffeeScript (not really field tested, yet):
Add class 'change_warning' to forms that should be watched for changes.
Add class 'change_allowed' to the save button.
change_warning.coffee:
window.ChangeWarning = {
save: ->
$(".change_warning").each (index,element) ->
$(element).data('serialized', $(element).serialize())
changed: (element) ->
$(element).serialize() != $(element).data('serialized')
changed_any: ->
$.makeArray($(".change_warning").map (index,element) -> ChangeWarning.changed(element)).some (f)->f
# AKA $(".change_warning").any (element) -> ChangeWarning.changed(element)
# But jQuery collections do not know the any/some method, yet (nor are they arrays)
change_allowed: ->
ChangeWarning.change_allowed_flag = true
beforeunload: ->
unless ChangeWarning.change_allowed_flag or not ChangeWarning.changed_any()
"You have unsaved changes"
}
$ ->
ChangeWarning.save()
$(".change_allowed").bind 'click', -> ChangeWarning.change_allowed()
$(window).bind 'beforeunload', -> ChangeWarning.beforeunload()
An alternative to Dw7's answer if you only want the fields inside a fieldset then you can call serialize() on its input values. Note: serialize() will not pickup any elements that do not have a "name" attribute. This will work for select tags as well.
var initialValues = $('#your-fieldset :input').serialize();
$('form').submit(function(e) {
e.preventDefault();
var currentValues = $('#your-fieldset :input').serialize();
if (currentValues == initialValues) {
// Nothing has changed
alert('Nothing was changed');
}
else {
this.submit();
}
});
.live is now deprecated and replaced by .on:
var confirmerSortie = false;
$(document).on('change', 'select', function() {
confirmerSortie = true;
});
$(document).on('change keypress', 'input', function() {
confirmerSortie = true;
});
$(document).on('change keypress', 'textarea', function() {
confirmerSortie = true;
});
The following solution worked for me:
$("#myDiv :input").change(function() { $("#myDiv").data("changed",true);});
}
if($("#myDiv").data("changed")) {
console.log('Form data changed hence proceed to submit');
}
else {
console.log('No change detected!');
}
Thanks