1

I am using the following code:

$('#theme').attr('href', $.cookie("jquery-ui-theme"));

This works if the cookie has already been set. But how can I make a default href if the cookie has not yet been se

Soviut
  • 88,194
  • 49
  • 192
  • 260
Jessica
  • 3,729
  • 4
  • 29
  • 29

4 Answers4

5

Strange to see suggestions here for a ternary operator in which the first value is the same as the condition. Shorten it to:

$('#theme').attr('href', $.cookie('jquery-ui-theme') || "default");

You can always reduce the ternary expression A ? A : B to the simpler A || B

Rob Davis
  • 15,597
  • 5
  • 45
  • 49
  • 2
    Also note that this is not particularly related to the jQuery cookie plugin but a general solution for default values – crackmigg Oct 23 '12 at 17:08
0

You could use a ternary operation which is essentially an if statement that fits on one line. They're structured as:

expression ? valueIfTrue : valueIfFalse;

I tend to use them for situations like this where you want a default value if something isn't set.

var href = $.cookie("jquery-ui-theme") ? $.cookie("jquery-ui-theme") : 'http://www.example.com';
$('#theme').attr('href', href);

This is equivalent to:

var href = $.cookie("jquery-ui-theme");
if (!href) {
    href = 'http://www.example.com';
}
$('#theme').attr('href', href);
Soviut
  • 88,194
  • 49
  • 192
  • 260
0

I'm not familiar with your cookie plugin, but just use a ternary operator (and modify this code for your plugin if needed):

$('#theme').attr('href', ($.cookie('jquery-ui-theme')!='') ? $.cookie('jquery-ui-theme') : 'your-default-value'))

See also: Operator precedence with Javascript Ternary operator

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
0

Check if it exists:

if ($.cookie('jquery-ui-theme') != null) {
  $('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
  $('#theme').attr('href', 'default');
}
Blender
  • 289,723
  • 53
  • 439
  • 496