is:empty not working for dynamically created content - javascript

I have a div listOfTodos that is empty by default. No white space inside the html. I also have a textbox that when enter is pressed it appends text to listOfTodos. For some reason is:empty doesn't work and it always says it's empty.
My code for checking is:
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
Then above this code I also have:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>'); }
});
The label above is saved and is retrieved on every reload. What's going on?

Doesn't JS run code from top to bottom? I have the keypress above the if statement inside my js file.
Yes, but the event handler is not executed until the event is triggered, which is not possible until after the whole script executed.
I.e.
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
}
});
if (....) { }
will execute the if statement only once after the event handler was bound.
You have to put the if statement inside the handler if you want to run it after the event fired:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
});
Or put it in a function if you want to run that logic in multiple places:
function isEmpty() {
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
// run on load
isEmpty();
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
// run on change
isEmpty();
}
});

Use
if ($.trim($('#listOfTodos').text()) == '') {
alert("empty");
} else {
alert("not empty");
}
Fiddle

Related

How to check if a textbox is clicked on

I have a keyup function on my script and when I type into one of my text boxes it triggers my hotkey which hides the text box so it makes it impossible to type in it. Please help.
$(document).keyup(function(e){
if(e.which == 67){
if($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
});
I want something like this but I don't know the right word to put here.
$(document).keyup(function(e){
if(e.which == 67){
if($("#chat-input").is("clickedOn")){
return false;
}
else{
if($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
}
});
you can do it by checking the active element in jquery . The code should be like $(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("id") == "chat-input")
Please let me know if it solves your problem
Try the following:
$(document).keyup(function(e) {
if(e.which == 67){
if (e.target.id == "chat-input") {
return false;
}
}
else {
if ($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
}
});

Onkeydown not working javascript

Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);

Jquery stop function when keypress

i am newbie with Jquery , i have this function :
$(document).ready(function()
{
$('*').keypress(function(e)
{
if(e.keyCode == 13)
{
$("[id^='td_']").click(function()
{
$(this).hide();
});
}
else
{
return false ;
}
});
});
If enter is pressed, i can click in some text to hide him.
The problem is that my function continue to run event if enter is not pressed.
return false do nothing .
Use the event.preventDefault(); to avoid this behavior
$(document).ready(function()
{
$('*').keypress(function(e)
{
if(e.keyCode == 13)
{
e.preventDefault();// this will block further keypress events
$("[id^='td_']").click(function()
{
$(this).hide();
});
}
else
{
return false ;
}
});
});
It looks like you want to press enter, then be able to click to do the hide, and then the click shouldn't run again until enter is pressed first. If that's the case, you can use .one():
$("[id^='td_']").one(function()
{
$(this).hide();
});
.one() will only allow the handler to be called once, then it will be removed.

jquery textbox focus event on infinity loop

i am using jquery to validate textbox value.
I have 2 textbox, txt1 & txt2. now, i wrote a jquery function.
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
Now, issue is. when i run the project. my position is on txt1 and when u use Tab to go txt2 with null or blank value. Focus event fire for both one & browser become hang due to infinite loop of FOCUS.
so, how can i handle it?
You should insert a setTimeout in order to set the focus after the blur event.
Second, you should insert a semaphore in order to avoid a loop (see code and comments):
var status = "valid"; // semaphore
$("#txt1").blur(function (e) {
// if we are in programmatically focus, ignore this handler
if(status == "invalid")
return ;
if ($("#txt1").val() == "") {
$("#scarriername").show();
// set semaphore
status = "invalid";
// use setTimeout in order to set focus in the right moment
setTimeout(function() {$("#txt1").focus(); status = "valid"},0);
}
else {
$("#scarriername").hide();
}
});
// same as txt1
$("#txt2").blur(function () {
if(status == "invalid")
return ;
if ($("#txt2").val() == "") {
$("#sscaccode").show();
setTimeout(function() {$("#txt2").focus(); status = "valid"},0);
}
else {
$("#sscaccode").hide();
}
});
DEMO http://jsfiddle.net/SszUf/
try this
<input type="text" id="txt1" />
<input type="text" id="txt2" />
$("#txt2").focus(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
//alert(1);
});
hope this help you
Apparently when you hit the tab button you trigger blur event for both text boxes. With your code when txt1 gets blurred and has no content you get the focus on txt1, but when you do that you also trigger the blur event for txt2 and since it does not have any text in it you get the focus back to txt2. This keeps on going and going, focusing on txt1 and then txt2 and then txt1 and then txt2... You could put a simple if check on the second blur event handler to see if txt1 is still empty, and if so keep the focus on txt1 not allowing the client to pass to txt2:
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "" && $("#txt1").val() != "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
This is also one of the approach to solve your problem on pressing tab key.
$("#txt1").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt1").val() == "") {
$("#scarriername").show();
return false;
}
else {
$("#scarriername").hide();
}
}
});
$("#txt2").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt2").val() == "") {
$("#sscaccode").show();
return false;
}
else {
$("#sscaccode").hide();
}
}
});
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
if ($("input:focus").length == 0)
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
Just add a line can solve this problem
By the way, the #scarriername should not be something like popup window, which will trigger other blur events
You can test the file below:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input id="txt1"><input id="txt2"><input id="txt3"><input id="txt4">
<hr>
<h1 id="h1"></h1>
</body>
<script type="text/javascript">
$(function(){
$("input").blur(function () {
if ($(this).val() == "") {
document.getElementById("h1").innerHTML += "123";
$(this).focus();
}
});});
</script>
</html>

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.

Categories

Resources