I have a list with a text input field $newItemField with the default value = "New Item". By clicking on an input button $addButton you can add the value of the $newItemField to the list.
When .focusin $newItemField I remove the default value to this.value = "";
When .focusout with $newItemdField = "" I reset the default value to $newItemField = "New Item". Both works just fine.
My question is, how can I combine the .focusout with a .focusin of a specific input field. In other words when .focusout wuth $newItemField = "" I only want to reset the default value when not clicked on $addButton????
What happens now is that when $newItemField ="" and I click $addButton the .focusout works first ($newItemField = "New Item") and then I add an item called "New Item" to the list. This is what I would like to prevent from happening.
I tried a lot using if and click(), but it didn't work. I would appreciate any form of support for my code below.
$newItemField.each(function() {
$(this).data('default', this.value);
})
.focusin(function() {
if (this.value == $(this).data('default')) {
this.value = '';
}
})
.focusout(function() {
if (this.value === ""){
this.value = $(this).data('default');
}
});
$addButton.click(function() {
addItem();
$newItemField.select();
});
Here my changes after William's answer. Now the §newItemField does not show any value after focusing out irrespective the .activeElement. In other words no I am missing the default value "New Item" when not clicking on the add button.
$newItemField.each(function() {
$(this).data('default', this.value);
})
.focusin(function() {
if (this.value == $(this).data('default')) {
this.value = '';
}
})
.focusout(function() {
setTimeout(function () {
if ($(document.activeElement).attr('id')!==$('add')//the id of the add button is #add
{
if ($newItemField.value === ""){
this.value = $(this).data('default');
}
}
}, 100);
});
You can use setTimeout inside the focusout function to check if the button has the focus and only change the value if it doesn't.
.focusout(function() {
setTimeout(function () {
if ($(document.activeElement).attr('id')!='$addButton')
{
//run code
//remember 'this' no longer refers to $newItemField
}
}, 100);
});
Try this:
.focusout(function() {
setTimeout(function () {
if ($(document.activeElement).attr('id') != ('add')) {
{
$(newItem).val('New Item');
}
}
}, 100);
});