Reputation: 3769
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
Upvotes: 1
Views: 3032
Reputation: 15772
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
Upvotes: 5
Reputation: 298106
Check if it exists:
if ($.cookie('jquery-ui-theme') != null) {
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
$('#theme').attr('href', 'default');
}
Upvotes: 0
Reputation: 163301
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
Upvotes: 0
Reputation: 91525
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);
Upvotes: 0