Focus button from javascript withour clicking it - javascript

I call
element.focus();
Where element is HTMLInputElement of type=button.
But then the browser clicks the button! That's in mozilla and chrome.
How do i highlight the button with selection, but not initiate the click event?

No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit
It does exactly what you want it to.

Well, i've identified the reason.
I was handling the onkeydown event for Enter key.
The solution is to use
e.preventDefault();
function ConvertEnterToTab(s, e, numSkipElements) {
var keyCode = e.keyCode || e.htmlEvent.keyCode;
if (keyCode === 13) {
var tabIndex = s.tabIndex || s.inputElement.tabIndex;
if (numSkipElements == undefined) {
numSkipElements = 0;
}
var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
if (nextElement != undefined) {
nextElement.focus();
return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
}
}
}
function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
if (maxTabIndex == undefined) {
maxTabIndex = 100;
}
var tempIndex = currentTabIndex + 1;
while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
tempIndex++;
}
return $('[tabindex=' + tempIndex + ']')[0];
}

Related

How can I use keyup and down true false

I have the following code to allow user to enter single digit code in an input box, if user presses delete key, then, I would like to recheck some condition and allow user type again. How do I do it?:
$('.code').bind('keyup', function(event) {
var value = $(this).val();
console.log("value.." + value.length);
if (value.length === 1) {
$('.InputInsertCodeLast').bind('keydown', function(event) {
var code = event.keyCode || event.which;
console.log('You pressed a "key" key in textbox' + event.keyCode);
if ((code === 8 || code === 46) || (value.length === 0)) {
return true;
} else {
//code to not allow any changes to be made to input field
return false;
}
});
} else if (value.length === 0) {
console.log("value.length,,0");
$('.InputInsertCodeLast').bind('keydown', function(event) {
console.log("value.length,22,0");
return true;
});
}
});
https://plnkr.co/edit/SpjcKkTA4UaJ0GzzEuYf?p=info
window.onload = function() {
window.addEventListener('keydown', function(event) {
event.preventDefault();
if(event.key === 'Backspace'){
console.log('backspace');
}
});
}
of course this is just a suggest to give an idea how things work, you can workout a more efficent solution based on this :)

Use Enter Keydown Event to move to the next Input

I have a large form. As users are filling in values I would like for the enter key to take on the same behavior as the tab key (i.e. I want to move the user to the next input element when the enter key is pressed.
Due to the way my HTML form is structured into various sections I cannot assume the next input is a sibling of the current input. Additionally, the classes and IDs of the inputs are not sequential.
jQuery:
$("input").bind("keydown", function (event) {
document.getElementById('keys').innerHTML = document.getElementById('keys').innerHTML + event.which + " ";
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
var e = $.Event("keydown");
e.which = 9;
$(this).trigger(e);
}
});
JSFIDDLE
This will do your job
$("input").not($(":button")).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit') {
var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
var index = fields.index(this);
if (index > -1 && (index + 1) < fields.length) {
fields.eq(index + 1).focus();
}
return false;
}
}
});
example

Textarea Shift+Enter for next line and Enter to submit the form

In textarea when the user presses Shift+Enter then it should continue in next new line and when he simply presses Enter it should submit the form without using submit button.
Here is the Fiddle!!
I have browsed a lot but doesn't helped me, detailed explanation appreciated
Please help me!!
Code
$('commenttextarea').keyup(function (event) {
if ( event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0,caret)+"\n"+content.substring(carent,content.length-1);
event.stopPropagation();
}else if(event.keyCode == 13)
{
$('commentform').submit();
}});
First, You missed to load any jquery version
Second, you missed # before textarea and form selectors.
Also use caret not carent in line
this.value = content.substring(0,caret)+"\n"+content.substring(caret,content.length-1);
// ----------------------------------^
Full Code
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$('#commenttextarea').keyup(function (event) {
if (event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0, caret) + "\n" + content.substring(caret, content.length - 1);
event.stopPropagation();
} else if (event.keyCode == 13) {
$('#commentform').submit();
}
});
See this would work
As Rohan Kumar said: you forgot the id Selectors:
$('#commenttextarea').keyup(function (event) {
if ( event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0,caret)+"\n"+content.substring(carent,content.length-1);
event.stopPropagation();
}else if(event.keyCode == 13)
{
$('#commentform').submit();
}});

How to stop the backspace for particular element in jquery or javascript?

I am new to javascript and I am making a web application. Basically its a simple memo using html5.
My html code:
<ul contenteditable="true">
<br/>abc<br/>
def<br/>
ghi<br/>
</ul>
and my javascript:
window.onkeydown = backspace;
function backspace() {
var key = event.keyCode || event.charCode;
var lis = document.getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
var li = lis[i];
if (li.innerHTML == "<br>") {
if (!li.id) {
li.id = "ttt";
if (key == 8) {
return false;
}
}
}
}
return true;
}
I tried the basic backspace return false but the problem is if the li tag is empty the other li tags will not take the backspace event even if it has a character.
you can add event handler to document keypress
then check if backspace and the type of element you want 'LI'
$(document).keypress(function(e) {
var key = e.which;
if (key == 8 && e.target.attributes[0].value != "text") {
return false;
}
});
you can can replace text with the type of element you want
$('input').keydown(function(e){
if(e.keyCode == 8) {
e.preventDefault();
alert('we arent allowing deletes');
}
});
http://jsfiddle.net/dq8tr/3/

Calling click from keydown, but getting the correct checkbox checked property

This isn't a jQuery only question as it has to do with events and order of operation. Consider the following code, which is based on jQuery multiSelect plugin (please post citation if you can find it):
Fiddle with it here
var debug = $('#debug');
var updateLog = function (msg){
debug.prepend(msg + '\n');
};
var title = $('#title').focus();
var container = $('#container');
title.keydown(function(e){
// up or down arrows
if (e.keyCode == 40 || e.keyCode == 38) {
var labels = container.find('label');
var idx_old = labels.index(labels.filter('.hover'));
var idx_new = -1;
if (idx_old < 0) {
container.find('label:first').addClass('hover');
} else if (e.keyCode == 40 && idx_old < labels.length - 1) {
idx_new = idx_old + 1;
} else if (e.keyCode == 38 && idx_old > 0) {
idx_new = idx_old - 1;
}
if (idx_new >= 0) {
jQuery(labels.get(idx_old)).removeClass('hover');
jQuery(labels.get(idx_new)).addClass('hover');
}
return false;
}
// space/return buttons
if (e.keyCode == 13 || e.keyCode == 32) {
var input_obj = container.find('label.hover input:checkbox');
input_obj.click();
return false;
}
});
// When the input is triggered with mouse
container
.find('input:checkbox')
.click(function(){
var cb = $(this);
var class = "checked";
if (cb.prop(class)){
cb.parent('label').addClass(class);
} else {
cb.parent('label').removeClass(class);
}
updateLog( cb.closest('label').text().split(/[\s\n]+/).join(' ') + ': '
+ this.checked + ' , '
+ cb.prop(class));
title.focus();
})
;
Notice the difference in the checkbox value for when you click directly on the checkbox, versus when you select the checkbox with the space/enter key. I believe this is because it's calling click during the keydown event, so the value of the checkbox is not yet changed; whereas if you actually click the input, the mouseup event occurs before the click (?), so the setting is applied.
The multiselect plugin does not call the click event, it has almost duplicate code. I'm curious if it would be better to pass a parameter to the click event (or use a global) to detect if it issued by the keyboard or mouse, or if it is better to just do what the plugin did and have the code inside the keydown function.
Obviously, if the log were after the click() runs, the keydown would return trues, but there are things that happen inside of click that are based on the input's checked status.
Changed it to use the change event instead of the click event for the checkboxes
http://jsfiddle.net/QJsPc/4/

Categories