I've got a html5 form and a submit button(original, I know).
When the user fills out the form incorrectly and presses the html < button ... /> tag, the focus goes to the first error message. This is expected and good behaviour and all is well.
However, when the user presses GO on both chrome and safari the focus does not move.
I tried debugging by printing out the document.activeElement after I set the focus.
It prints the same html element when I press go and when I press the form button, even though the focus is not on this particular element when i press GO.
In short:
Press HTML button - use jquery to apply focus to desired error input. Works like a charm.
Press GO button - use same function to apply focus to the desired error input.
The user does not get anything.
Code examples:
Markup:
<form class="boxBody form" action="#" id="profileForm">
<input type="text" class="keyboardInput" id="customer-email" name="email" tabindex="1" size="28" maxlength="128">
//More inputs
<button id="profileSubmit" data-localize="{'text': 'profileBox.submit'}" tabindex="11" class="save-profile btn btn-red"></button>
</form>
.js:
$('#profileForm').submit(function(event)
{
event.preventDefault();
updateProfile(event);
//updateProfile validates the form and creates error messages
setFocusOnUpdate();
console.log(document.activeElement);
//prints the same dom element.
});
And
function setFocusOnUpdate(){
var successMessage = $(".alert-success:visible", widgetElement);
if( successMessage.length > 0 )
{
//Success message gets focus
widgetElement.find("input, select").last().focus();
}
else
{
//First error message gets focus
var firstVisibleAlert = $(".alert:visible", widgetElement)[0];
$(firstVisibleAlert).parent().find("input, select").focus();
}
}
Thing is, in both instances, GO and < button / >, the desired element gets focus, but the screen only moves to the element when I use the button. How can I get the screen to move when pressing go also?
Can some wizard please help me? Any ideas appreciated!
Have you tried using anchors on the same page to get your desired effect?
Isn't it possible to set anchors by the forms so that when you want the focus to be set too a certain input it does so by moving your screen to the anchor?
Related
Take this HTML code, if you place your cursor on the 1st text-box, and then press Tab Key. The cursor will automatically jump to the 2nd text-box.
Box1:
<textarea id='box' cols='60' rows='10'></textarea>
Box2:
<textarea id='box' cols='60' rows='10'></textarea>
I need to replace this default action of switching to the next textbox with execution of JavaScript function I've defined. Let's say: instead of switching textboxes execute function that writes 'a' on the the 1st text-box upon pressing Tab inside the box.
Any idea how I can make this happen?
You would need to listen to the keydown event (tested the others they do not work for this specific case). From there you need to check if tab was pressed. Then you would need to prevent the default from happening and finally execute your custom logic. In the example down below the default functionality of tab is only then overwritten if the first textarea is focussed.
<textarea id="box1"></textarea>
<textarea id="box2"></textarea>
document.getElementById("box1").addEventListener("keydown", (event) => {
if (event.keyCode === 9) {
event.preventDefault();
event.target.value += "a"; // adding a to textarea (your example)
}
})
I made a simple calculator.
User can enter a value in an input-field, then click the '+' button.
The focus remains on the input-field, so the user directly can enter a new value after clicking on the +. The mouse position remains on the '+' button, so he can click again after entering a new value.
However, clicking this time, no event at all is fired. After approx. 1 second it is possible again, the click is fired. Please explain.
N.b. I experience the same behaviour with online calculators, e.g. http://web2.0calc.com/
The html code:
<input type='text' id=calc size=14 style='text-align:right' ></input>
<button type='button' onclick= 'Plus()'>+</button>
and script:
// init:
document.getElementById('calc').value = ''
document.getElementById('calc').focus()
//
function Plus(){
// check input, add to total
document.getElementById('calc').value = '' // clears input after add
document.getElementById('calc').focus() // keeps focus on input
}
The example link you gave works perfectly fine in my machine. The delay of 1s that you mention might be a performance issue because of old browser, slow machine etc.
How do I put focus on a textbox with JavaScript(Or jQuery)?
I have a textbox on a page and after the user presses the enter key, the textbox loses focus. (Keep in mind that no post occurs, the page does not refresh)
I want to be able set the focus back inside of the textbox through javascript so that the user can continue typing and doesn't have to click on anything.
I tried adding the following code after the users has pressed the enter key:
$(".focus").focus();
The code for my textbox:
<input type="text" class="focus" />
but alas, the cursor does not appear inside of the textbox and the user still has to click to continue typing.
How do I fix this problem?
You have to apply the focus code to the input, if the page hasn't loaded or the DOM isn't ready when the code runs, then there's no input yet to focus on..
So you have to check that the DOM is loaded, like this:
$(function(){
$(".focus").focus();
});
http://jsfiddle.net/c7aUS/
You can also include the code at the bottom of the page, before the </body> tag, so that it loads right after all your HTML.
note: If you're running this in jsfiddle, by default your code is run on page load. When using JQuery, it automatically wraps it in this code:
$(window).load(function(){
//your code here
});
EDIT:
In that case, meetamit is very helpful, I think you're looking for this:
$(function(){
$(".focus").focus();
$(".focus").on('keydown', function(event) {
if(event.which == 13) {// Enter key pressed
$this = $(this);
$this.focus();
var value = $this.val();
$this.val(''); /* clear the field */
// do stuff with the value
}
});
});
http://jsfiddle.net/c7aUS/1/
Why does pressing the enter key take away the focus from the field? (I couldn't reproduce it.) It might suggest that there's a hidden problem still. Maybe not. If not, this might help:
$(".focus").on('keydown', function(event) {
if(event.which == 13) {// Enter key pressed
event.preventDefault();
}
});
I have a search textbox in the web page. When the user presses enter key after entering text in that textbox then the search function should get executed. How to do this?
Check the onkeypress event of this and look for the keycode 13. Once keycode 13 is hit fire a click of a hidden button and do programming on the back end of the event of that hidden button.
If there's only one input field in a form, then the form will submit when you press enter even if there's no 'Submit' button.
eg
<form action="/search">
<input type="text" value="search text">
</form>
will submit when enter is pressed.
If that is the only textfield in your form, then pressing enter causes the onsubmit handler to run. But that will submit the entire page. If you want to perform an ajax command onsubmit and not refresh the whole page, then make sure your onsubmit handler returns false.
To do a regular full page form submit when enter is pressed:
<form action="/doit">
<input type="text" value=""/>
</form>
To do an ajax form submit when enter is pressed, something like this jquery code could be used:
$("form").submit(function() {
$.ajax(...);
return false;
});
basically u can do it like this:
i like to use jquery for most javascript stuff for cross browsers compatibility.
$("#btnID").keypress(function(event){
//filter enter key only
if(event.keyCode == 13){
//do something here
}
return true;
});
I have implemented this functionality very easily! I have a search textbox and a button with style ="display:none". These controls are surrounded by an ASP panel, I have set DefaultButton property of the panel as the button's ID. Now on entering text and pressing enter key the search functionality present in the button click event gets executed and also the button is also not visible to the user's!!!
I want my (ExtJS) toolbar buttons not to grab the focus on the web page when they are clicked, but to do their "thing" while leaving the focus unchanged by the click. How do I do that?
Cancelling the default behavior of onmousedown prevents an element from getting the focus:
// Prevent capturing focus by the button.
$('button').on('mousedown',
/** #param {!jQuery.Event} event */
function(event) {
event.preventDefault();
}
);
document.activeElement stores the currently focussed element.
So on your toolbar, you can add a "mousedown" handler to this function :
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
Try this example :
<html>
<head>
<script>
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
</script>
</head>
<body>
<input type="text"/>
<input type="button" onmousedown="preventFocus()" onclick="alert('clicked')" value="Toolbar" />
</body>
</html>
This usually does the trick for me:
<button
tabindex="-1"
onclick="javascript:console.log('do your thing')"
>My Button</button>
From https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex:
A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. It's mostly useful to create accessible widgets with JavaScript.
I don't think there's an easy way to do what you want to do because it's the browser's default behaviour.
You could of course blur() the button as soon as it is clicked, but that would simply unselect everything. To have the previously active object regain focus, you'd have to create a "memory" of sorts by adding a blur handler for every element to keep track of which element had/lost focus last (store the id of the element in a global and update it when an element loses focus).
The top-voted answer is technically correct, but depends on jQuery...
Here's a simpler example:
<span onclick="document.execCommand('bold', false);" onmousedown="event.preventDefault();"></span>
My solution is to replace <button /> with <div /> and style it as a button.
Looks like Div doesn't take a focus on it when you click it.
Because the toolbar buttons are just styled ordinary HTML button elements then this is an actual browser behavior, and you should think twice before changing it. But nevertheless...
You should be able to prevent the botton from receiving focus by just returning false from its onclick handler.
Maybe you should try to use stateful and state change properties for form fields or whatever to get focus back?
I would attach one blur event listener to all fields. This listener should save the field, that lost the focus, in a global variable.
Then all the toolbar button should get one focus event listener. This listener should focus the field, that was saved as described above.
This code should work, although it didn't test it
<script>
function focusor(){
document.getElementById('focus').focus;
}
document.onkeydown = focusor;
document.onclick = focusor;
</script>
<div style="width: 0px; height: 0px; overflow: hiddden;">
<button id="focus"></button>
</div>
What I have found, is you will have to make a dummy element, I found buttons to work best in this situation. put the button in a div and make the div 0px.
[do not make the div display none, some browsers will just ignore it]
Basically any click or button presses, it will focus on this dummy button.
I had a project very similar and whenever they pressed the down key it selected the first button on the page, this just focuses on the button over and over again.
Sort of jacked up, but it works.
All these answers are wack. Here's a very excellent trick that only uses CSS
<button type="submit" disabled>
<span>Submit</span> <!-- the <span> is the secret -->
</button>
Now in your css:
button[disabled] > * {
pointer-events: none;
}
The trick is the inner span has to be used, otherwise the button will still steal focus away from inputs.