Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if var is not empty with javascript?

Tags:

javascript

Not having much luck with this. I'm trying to determine if a var is not empty.

$('#content').mouseup(function() {

    var selection = getSelected();

    if (typeof(selection) !=='undefined') {
        alert(selection);
    }
});

What this is doing is grabbing any text the user has selected -- but it shows an empty alert even if the user just mouseup's on the div.

like image 527
Mike Avatar asked Apr 01 '11 22:04

Mike


1 Answers

Your code is perfectly accurate for detecting an undefined value, which means that the function always returns some kind of value even if there is no selection.

If the function for example returns a selection object (like the window.getSelection function), you check the isCollapsed property to see if the selection is empty:

if (!selection.isCollapsed) ...
like image 126
Guffa Avatar answered Oct 19 '22 23:10

Guffa