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
  • 83,904
  • 44
  • 175
  • 239
Jessica
  • 3,679
  • 4
  • 26
  • 28

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,197
  • 5
  • 43
  • 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
  • 83,904
  • 44
  • 175
  • 239
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
  • 152,561
  • 47
  • 332
  • 504
0

Check if it exists:

if ($.cookie('jquery-ui-theme') != null) {
  $('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
  $('#theme').attr('href', 'default');
}
Blender
  • 275,078
  • 51
  • 420
  • 480