Reputation: 13467
I'm using a heavily modified version of jquery-tokeninput
it's essentially a text input box that allows multiple tags just like stack overflow.
You can get a return value with all the tags currently in the input by running this:
$("#no-custom-tokens").tokenInput("get")
The problem is, it returns the following for me:
if i try to call $("#no-custom-tokens").tokenInput("get").length
it just says undefined.
I need to check if there are any u1, u2, etc inside this object (basically.. is the input blank).
I have considered doing...
if ($("#no-custom-tokens").tokenInput("get").u1.name != "")
Except that if you delete tokens, then add 2 more, it doesnt start at u1, u2... it starts at u3 and u4.
:/
Upvotes: 0
Views: 95
Reputation: 546503
Check if it's empty:
function isEmpty(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) return false;
}
return true;
}
Check its length:
function objectLength(obj) {
var size = 0;
for (var i in obj) {
if (obj.hasOwnProperty(i)) ++size;
}
return size;
}
// or:
function objectLength(obj) {
return Object.keys(obj).length;
}
Upvotes: 1
Reputation: 1293
It looks like it's returning as an object, not an array, so there is no .length method. If you just want to check if anything's in the object, you can try to loop through the object and set a flag if it finds anything. So:
var isEmpty = true;
var tokens = $("#no-custom-tokens").tokenInput("get");
for (var i in tokens) {
isEmpty = false;
break;
}
if (isEmpty) {
...
}
Upvotes: 1
Reputation:
"I need to check if there are any u1, u2, etc inside this object (basically.. is the input blank)."
If you basically need to check for the existence of at least one property, and if the properties are enumerable, you can do this...
var has_props = false,
obj = $("#no-custom-tokens").tokenInput("get");
for (var p in obj) {
has_props = true;
break;
}
console.log(has_props);
If you want to know how many, and again, if they're enumerable, you can use Object.keys
...
var props_len = Object.keys($("#no-custom-tokens").tokenInput("get")).length;
You'll just need to shim it if you're supporting older browsers...
if (!Object.keys)
Object.keys = function(o) {
var keys = [];
for (var k in o)
if (o.hasOwnProperty(k))
keys.push(k);
return keys;
};
Upvotes: 1