jQuery change focus on tab or focusout - javascript

(sorry for my english)
Hi!, i'm using jquery in an app where i have a dinamycally created table with text inputs inside like this:
<td><input type="text" id="code"></td>
<td><select id="type"><option value="0">Normal</option><option value="1">Other</option></select></td>
<td><input type="text" id="price" class="price"></td>
<td><input type="text" id="total"></td>
and in other part i have a button, when this button is clicked, create another line in the table.
The container of this table and button exists inside a template.. this templates is rendered using underscore.js
Now the problem: I need to iterate over the inputs in order: code, type, price. When i fill the input price i calculate the total and shows up in the input, and then i need to change focus to the button (#more_button) to let the user click or press enter to create another line in table.
I use this:
$('.price').blur(function(e){
_this.setTotal($(e.currentTarget).val());
$('#more_button').removeClass('inactive').focus();
e.preventDefault();
e.stopPropagation();
});
When the #more_button is focused the css background change.
When i execute this piece of code, the button change the background but the focus inmediatly change to url bar. This happend in firefox and Chrome.
I try to use this to set the focus:
$('.price').blur(function(e){
_this.setTotal($(e.currentTarget).val());
$('#more_button').removeClass('inactive').;
setTiemout(function(){
$('#more_button').focus();
},100);
e.preventDefault();
e.stopPropagation();
});
But don't work either.....
Can you give some guideline to acomplish this?
The user can change the focus of input.price when press Tab or click in other part of the page.. in this moment i need to trigget seTotal and focus on the button.

I don't know what the simple method
$('your_selector').focusout(function(){
$('#more_button').focus();
});
doesn't work with tab key (only with the mouse to change the focus).. so i solve using a mix between keydown event and focusout. like this:
$('.price').bind('keydown',function(e){
if(e.keyCode === 9){//Tab key
tab = true;
check(e);
return false;
}
}).bind('focusout',function(e){
if(!tab){
check(e);
}else{
tab = false;
}
e.preventDefault();
return false;
});
where check() is a function to validate the value and tab is a flag to check if the tab key was pressed.

$('your_selector').focusout(function(){
$('#more_button').focus();
});
works in FF and chrome here at least.
here a fiddle: http://jsfiddle.net/Zabn4/

The most modern solution (jQuery 1.7+) is to use the following code:
$('#your-input').on('focusout', function(e){
$('#submit-btn').focus();
});

Related

Safari issue with text inputs, text is selected as user enters it causing text to be lost

I have the following input element on my page:
<input class="input" name="custom_fields[new]" placeholder="Enter placeholder" type="text">
I have a Twitter Flight event listener on this element that looks like this:
this.on('keyup', {
inputsSelector: this.updateViewInputs
});
Which triggers this method:
this.updateViewInputs = function(ev) {
var isDeletionKeycode = (ev.keyCode == 8 || ev.keyCode == 46);
// Remove field is user is trying to delete it
if (isDeletionKeycode && this.shouldDeleteInput(ev.target.value, this.select('inputsSelector').length)) {
$(ev.target.parentNode).remove();
}
// Add another field dynamically
if (this.select('lastInputsSelector')[0] && (ev.target == this.select('lastInputSelector')[0]) && !isDeletionKeycode) {
this.select('inputsContainer').append(InputTemplate());
}
// Render fields
that.trigger('uiUpdateInputs', {
inputs: that.collectInputs()
});
}
And finally triggers uiUpdateInputs:
this.after('initialize', function() {
this.on(document, 'uiUpdateInputs', this.updateInputs)
});
this.updateInputs = function(ev, data) {
// Render all inputs provided by user
this.select('inputListSelector').html(InputsTemplate({ inputs: data.inputs }));
}
All of this functionality works as expected on Chrome and Firefox. Users can type into the input and see the page change in 'real time'. Users also get additional fields that they can enter text into and see the page change.
The issue in question arises when using Safari, as a user enters text into the described input field the text in the input field becomes highlighted (selected) and when they enter the next character all the content is replaced with that single character. This results in the user not being able to enter more than 1 or 2 characters before having them all replaced by the next entered character.
I have tried several approaches to fix this problem but none have worked, they include:
Using a setTimeout to delay the code run on the keyup event
Using Selection to try to disable the selection of the text using collapseToEnd.
Using click,focus,blur events to try to remove the selection from the entered text
Triggering a right arrow key event to try to simply move the cursor forward so they user does not delete the selected text
Using setInterval to routinely remove selections made by the window
I am very confused why this is happening and I am wondering if this is a bug in webkit with Flight. I see no issue with the Firefox or Chrome versions of this page. Thanks for any help!
This seems to be an issue with certain versions of Safari. When listening for the keyup function in javascript it will automatically select all of the text in the box and subsequently delete it all when the next key is typed. To prevent this from happening call preventDefault on the event object that is passed to the keyup function.
this.on('keyup', function(e) {
e.preventDefault()
});

jQuery not capturing click event following trigger call on HTML radio button

I have a very strange issue with jQuery where I am triggering a click on a radio button but it is not firing completely and is not being captured by an on click function, however a similar call to jQuery trigger is being captured.
In the following jQuery I am selecting a <div> and using find to search for the suitable content.
var prev_chosen_d_option = $('#d_options_table .d_option_row[data-option-id="' + d_option_for_jq + '"]');
// this works, and the on click is captured
prev_chosen_d_option.find('.hover_target').trigger("click", true);
// this selects the radio button, but DOES NOT fire the on click function seen below
prev_chosen_d_option.find('#d_standard_use_b_as_s_no').trigger("click", true);
These are my radio buttons:
<input type="radio" value="yes" id="d_standard_use_b_as_s_yes" name="d_standard_use_b_as_s">
<input type="radio" value="no" id="d_standard_use_b_as_s_no" name="d_standard_use_b_as_s">
$("#d_options_table .d_option_row .hover_target").on("click", function(e, isFirstLoad) {
// it comes in here fine!
});
$('input[name=d_standard_use_b_as_s], input[name=d_next_day_use_b_as_s], #del_standard_use_b_as_s_no').on("click", function(e, isFirstLoad) {
// it DOESN'T come in here
});
I can't see how jQuery is able to select the radio button and successfully check it, but the on method doesn't pick it up as a click...especially when I have a very similar setup running in close proximity in the code.
I know for sure that the radio buttons are within the selector as I can dump it out to the console with a console.log. Interestingly, when I dump out the events attached to it to the console I get undefined from this after the trigger:
console.log(prev_chosen_d_option.find("#_standard_use_b_as_s_no").data('events'));
(I am using jQuery 1.7.2 and testing in FF).
Instead of
$('input[name=del_standard_use_b_as_s], input[name=del_next_day_use_b_as_s], #del_standard_use_b_as_s_no').on('click', function(e) {
//
});
Try :
$(document).on('click', 'input[name=del_standard_use_b_as_s], input[name=del_next_day_use_b_as_s], #del_standard_use_b_as_s_no', function(e) {
//
});
The reason for this not working was simply I had the click handler below where I was actually triggering the click in the code.

HTML text input select all content on focus not working in chrome

I have a bunch of text inputs each inside a table cell like this:
<td class="tdTextInput">
<input type="text" value="0" name="txt1_9_4_2" id="txt1_9_4_2" class="input-supermini">
</td>
Whenever the user clicks on the cell or the input it must automatically select all the content inside the input (kind of like a spreadsheet editor).
So here is the script that so far achieves it successfully only in trusty old Firefox.
//focus the textbox on td click
$('.tdTextInput').mousedown(function ()
{
$(this).find('input').first().focus();
});
//select all text on focus
$('.tdTextInput input').focus(function ()
{
//the data-selected attribute is used to prevent the
// autoselection to happen more than once per cell so that
// two consecutive clicks will allow the user to pinpoint the
// cursor to a specific position
var isSelected = $(this).attr('data-selected') == 'true';
if (!isSelected) {
$('input[data-selected]').removeAttr('data-selected');
$(this).attr('data-selected', 'true');
$(this).select();
}
});
//prevent non-numeric values from being added
$('.tdTextInput input').keydown(function (e)
{
CommonTools.IsNumeric(e);
});
CommonTools.IsNumeric refers to the following: -(probably not relevant though since the keydown function is not the issue. Only adding it in the question for completeness)
isNumeric = function (e)
{
if(!(e.which>=48 && e.which<=57)) //numeric values only
e.preventDefault();
}
Why is this only working in FF and IE and not in Chrome?
UPDATE:
I've created a fiddle here: http://jsfiddle.net/dDc73/, however it doesn't even work in FF or IE in the fiddle either.
Some more info:
When I click on the cell it selects all the text until I release the mouse click.
Refrence:
Selecting text on focus using jQuery not working in Safari and Chrome
$(".tdTextInput input").mouseup(function(e){
e.preventDefault();
});
this also might be of help:
Select all text on focus using jQuery
$(".tdTextInput input").live('mouseup', function () {
$(this).select();
});
Let the "First name" input field automatically get focus when the page loads:
<form action="demo_form.asp">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
<input type="submit">
</form>

Javascript (jQuery) / HTML: Setting an <input> or <select> to enabled, not working?

I'm currently using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (latest I think).
My code goes something like this: http://jsfiddle.net/SVtDj/
Here's what I want to happen:
Enter something on input1
Click the disabled input (to trigger the onchange function... see jQuery)
NOTE: After inputting stuff on input1, we click the disabled input, nothing else.
The disabled input should now be enabled. Since by clicking the disabled input, it should trigger the input1's onchange function.
This works in Google Chrome, however, it doesn't work on Mozilla Firefox. How come clicking on the disabled element does not trigger the input's onchange function? This also applies to clicking a disabled instead of a disabled
Disabled inputs do not trigger change and click events on FireFox.
$('li:eq(1)').click(function(e){
if($.trim($('#input1').val()).length != 0){
$('#input2').prop('disabled', false);
}
});
http://jsfiddle.net/SVtDj/10/
instead of trim() you can use jQuery $.trim()function which is cross-browser:
$('#input1').change(function(){
if($.trim($(this).val()).length != 0){
$('#input2').prop('disabled', false);
}
});
demo
Your code is fine. The issue is that .change() requires a lost of focus (blur) before it triggers. Try changing it to .keyup()
http://jsfiddle.net/SVtDj/6/
additional: this is probably the effect you were going for
$('#input1').keyup(function(){
$('#input2').prop('disabled', $(this).val().trim().length == 0);
});​
To extend Ramison's answer
If you want to toggle the disability on #input2 you can simple:
$('#input1').change(function(){
var isDisabled = !$.trim($(this).val()).length;
$('#input2').prop('disabled', isDisabled );
});
And the demo: http://jsfiddle.net/SVtDj/7/
The issue is Firefox needs you type 'enter' or do something else so input1 looses the focus after having wrote in input1 to cast the "onchange" event I think. Maybe this question is linked to yours, and it made me try the following that works with Firefox. (I didn't try it on other browsers)
$('#input1').bind('input',function(){
if($(this).val().trim().length != 0){
$('#input2').removeAttr('disabled');
}
});​
That's because in FF, when an input is disabled it is really disabled (it doesn't receive mouse clicks).
Clicking on your disabled element doen't produces a blur event (focus lost) on input1, so the onchange doesn't gets fired.
You can workaround this easily with some classes and jQuery. For example:
<input class=disabled id=input2>
some css:
.disabled { background: #888; }
and then...
$(function(){
// disable keypresses on "disabled" input
$('.disabled').keypress(function(e){
e.preventDefault;
e.stopPropagation;
return false;
});
// doesn't allow to focus
$('.disabled').focus(function(e){
$(this).blur();
});
});
to activate the "disabled" element:
$('#input2').removeClass('disabled');
Check it here: http://jsfiddle.net/SVtDj/11/
See the answer of #Andy E in this post Jquery event on a disabled input, i think it is the best solution to resolve your problem.

Prevent an element from losing focus

We have a lot of inputs in a document.
We want to open a dialog that generates text and puts that in the currently focused input.
The problem is that, when I click a button or anything else to open the dialog that input loses focus. I can't determine which input has to get the generated text.
$("#button").click(function(){
// something should goes here to prevent stealing inputs focus
});
Is there any solution to prevent stealing focus by that special button?
You could not use a form button and just use say a <span> make it behave like a button?
UPDATE:
You could use something like
$('span').hover(function(){
focused_element = $("*:focus").get(0);
});
$('span').click(function(){
focused_element.focus();
});
Check out my fiddle
Does your field have a unique ID? If it does, use that ID to set the focus back to the field when the dialog's save/close button is clicked.
Don't worry about having the focus stolen as much as resetting it once you are done.
My solution would be to handle every focus and save it in focusEle:
$(function () {
var focusEle;
$('*').focus(function () {
focusEle = this;
});
$('button').click(function (e) {
console.log(focusEle);
var c = confirm('Love the cat :3?');
$(focusEle).focus();
});
});
With HTML as:
<input type="text">
<button>Press me!</button>
Example is working: http://jsfiddle.net/76uv7/
Depending on #ggzone idea

Categories