Set focus on textfield when un-focused - javascript

I want a text field to always be focused. When they click out of the textfield, I want the focus to go back into the textfield.
How would I accomplish this with jQuery?
$('input').focus();
$('input').**unfocused?**( function($) { $('input').focus();} );

You're looking for the blur event:
$(':text').blur(function() { this.focus(); });

The following code is an alternative solution which depends on periodically checking the control's state.
var controlFocus=false;
$("#txtName").focus(function(){
$(this).addClass("focused");
if(!controlFocus) {
controlFocus = true;
setInterval(function(){
var o = $("#txtName");
if(!o.hasClass("focused")) o.focus();
}), 200);
}
}).blur(function(){$(this).removeClass("focused");});
After the textbox (named txtName) gets its first focus, every 0.2 second, the code controls whether the textbox has focus. If it doesn't, it's focused. But this can be a really annoying thing.

Bind to get the change event, and check if focus must be forced to this input if so, insert some data in the document. $(document).data(‘_force_focus’, e.target)
$('input.force').bind('change', function(e) {
if( need_force_focus() ) {
$(document).data('_force_focus', e.target);
} else {
$(document).removeData('_force_focus');
}
});
Now on the document bind to the focusin event, testing if document have the “_force_focus” data. If so set the focus to the value. It’s important prevent the focusin retrigger by testing against e.target
$(document).bind('focusin', function (e) {
var t = $.data(document, '_force_focus');
if( t && e.target !== t ) {
$(t).trigger('focus');
return false;
}
return true;
});

Related

Kendo toolbar button not firing click event after being enabled

This is my logic, here I am trying to disable the save changes button and prevent click event on it if the user enters a duplicate value and enable it again if the user changes the values but after enabling it the update / save event does not occur am I doing something wrong? This is my code
function OnChange(data) {
//data.preventDefault();
$(".k-grid-save-changes")
.attr("role", "button")
.removeClass("k-state-disabled")
//.addClass("k-grid-save-changes")
.click(function () {
return true;
});
//console.log("data", data.items["0"].ProviderTypeName);
var name = data.items["0"].ProviderTypeName;
var Id = data.items["0"].Id;
var grid = $("#grid").data("kendoGrid");
//console.log("Grid ", grid);
grid.tbody.find('>tr').each(
function () {
$(this).css('background', 'white');
var dataItem = grid.dataItem(this);
//console.log(dataItem.ProviderTypeName)
if (dataItem.ProviderTypeName == name && dataItem.Id != Id) {
$(this).css('background', 'red');
$(".k-grid-save-changes")
//.removeClass("k-grid-save-changes")
.addClass("k-state-disabled")
//.removeAttr("role")
.click(function () {
return false;
});
}
});
}
This is where is call the on change event
.Events(events => events.RequestStart("OnRequestStart").Change("OnChange").RequestEnd("OnRequestEnd").Error("onError"))
If I remove the "return false;" it is working as expected but this allows duplicated values to be saved. So I have used this.
If I understand correctly in your code you do exactly what you mention as a problem. At every change you disable the save functionality with the return false. You don't enable it again at any point.
If you add an event handler to the button then you have to undo it at a later point. Since though I don't believe that the validation should occur at the change event but at the button click I would suggest to use the grid Save event where you could iterate dataSource.data() of your grid (much better) do your check and if anything happens return false.
One other way to go since you probably want the css effect with the background is to keep your code and discard the click event. Just set a flag that you could use in the save event. Something like this:
if(// your control){
$(this).css('background', 'red');
duplicatedValue = true;
}else{
.removeClass("k-grid-save-changes");
duplicatedValue = false;
}
And in the save event
function onSave(){
if(duplicatedValue){
return false;
}
}

when removing a child element I get an error that it may have already been removed in a "blur" event

I have a dynamic element added to a LI element. When I remove it in a "blur" event it works fine. But when I attempt to remove the element from the parent in a "keydown" event it throws an error that the child may already have been removed in a blur event.
The item is removed as expected and the flow continues but I get an error every time on the "keydown" event.
// I get the error in this event.
input.addEventListener('keydown', function (event) {
if (event.keyCode === 13) {
value = this.value;
this.parentElement.removeChild(this);
callBack.call(null,[value]);
}
});
//no error removing the element here
input.addEventListener('blur', function (event) {
value = this.value;
this.parentElement.removeChild(this);
callBack.call(null,[value]);
});
When you trigger the blur event on the input, only the blur event fires.
When you trigger the keydown event that removes the input, the blur event also fires as a consequence of that removal, and tries to remove an input that is already gone.
To see this in action, check out this example:
http://jsfiddle.net/nate/kDKVy/
var input = document.getElementById('foo');
var valueDisplay = document.getElementById('value');
var value;
input.addEventListener('keydown', function (event) {
if (event.keyCode === 13) {
value = this.value;
valueDisplay.value = value;
this.parentElement.removeChild(this);
}
});
input.addEventListener('blur', function (event) {
console.log('BLUR');
value = this.value;
valueDisplay.value = value;
this.parentElement.removeChild(this);
});
Open up your console. First, type something in the red box and then click away to trigger the blur event. Notice that it works nicely and you see "BLUR" in the console.
Run the fiddle again. Now, type something in the red box and hit enter. Notice that you get the "BLUR" message in your console before the error.
Make sense?

X-Editable: stop propagation on "click to edit"

I have an editable element inside a div which itself is clickable. Whenever I click the x-editable anchor element, the click bubbles up the DOM and triggers a click on the parent div. How can I prevent that? I know it's possible to stop this with jQuery's stopPropagation() but where would I call this method?
Here's the JSFiddle with the problem: http://jsfiddle.net/4RZvV/ . To replicate click on the editable values and you'll see that the containing div will catch a click event. This also happens when I click anywhere on the x-editable popup and I'd like to prevent that as well.
EDIT after lightswitch05 answer
I have multiple dynamic DIVs which should be selectable so I couldn't use a global variable. I added an attribute to the .editable-click anchors which get's changed instead.
editable-active is used to know if the popup is open or not
editable-activateable is used instead to know if that .editable-click anchor should be treated like it is
$(document).on('shown', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).attr("editable-active", true);
});
$(document).on('hidden', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).removeAttr("editable-active");
});
The check is pretty much like you've described it
$(document).on("click", ".version", function() {
$this = $(this)
// Check that the xeditable popup is not open
if($this.find("a[editable-active]").length === 0) { // means that editable popup is not open so we can do the stuff
// ... do stuff ...
}
})
For the click on the links, simply catch the click event and stop it:
$("a.editable-click").click(function(e){
e.stopPropagation();
});
The clicks within X-editable are a bit trickier. One way is to save a flag on weather the X-editable window is open or not, and only take action if X-editable is closed
var editableActive = false;
$("a.editable-click").on('shown', function(e, reason) {
editableActive = true;
});
$("a.editable-click").on('hidden', function(e, reason) {
editableActive = false;
});
$("div.version").click(function(e) {
var $this;
$this = $(this);
if(editableActive === false){
if ($this.hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
}
});
Fixed Fiddle
It's not pretty, but we solved this problem with something like:
$('.some-class').click(function(event) {
if(event.target.tagName === "A" || event.target.tagName === "INPUT" || event.target.tagName === "BUTTON"){
return;
}
We're still looking for a solution that doesn't require a specific list of tagNames that are okay to click on.

Why doesn't jQuery function properly on keydown?

I have this external jQuery code:
jQuery(document).one('keydown', 'g',function (evt){
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
return false;});
There are no errors in console.
I know it's rather silly, but never mind the text in .html(). Anyways, whenever I go to the webpage it just replaces the default 0 in the page with nothing. Then, when I press any key nothing happens. Ultimately, what I want this script to do in the end is display the letter or number that the user types in the tb div.
P.S. I'm new to stackoverflow so please tell me if my formatting is wrong or if I broke a rule.
Okay, so I edited the code and here is what I have:
$('#tb').on("keydown", function(event) {
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
});
It still doesn't work.
A div element does not have a keydown event. Only element that have focus property can have it.
So I think you are referring to a input inside the div..
HTML
<div id="tb">
<span class="output"></span>
<input type="text" />
</div>
JS
// Delegating the event on input to it's container
$('#tb').on("keydown", 'input', function (event) {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
});
Check Fiddle
// Bind event to the document which fires when document is focussed and
// a key is pressed
$(document).on('keydown', function(event) {
// Key code for g
if(event.keyCode === 71) {
// Bind the event to the input when g is pressed
$('#tb input').on('keyup', inputKeydown);
// unbind the event on document as no longet necessary
$(document).off('keydown');
}
return;
});
function inputKeydown() {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
}
Another Fiddle

Do not fire one event if already fired another

I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});​
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});

Categories

Resources