Ahmed Syed
Ahmed Syed

Reputation: 1189

How to write conditional window.location.href

I have following javascript line for redirection of webpage.

 window.location.href ="<?php echo $this->url->link('product/category', 
'path=' . $data['category_id']);?>_"+child_select; 

child_select is a javascript variable. I want to display _child_select i.e.undescore and whatever child_select value only if it present.

and I have to do it in same statement without repeating the code. How can I do that?

Upvotes: 0

Views: 1365

Answers (2)

Tushar
Tushar

Reputation: 87203

You can use Conditional/Ternary operator ? : to check if the child_select is present. If not use the URL without _ and child_select.

Set the value of Base path in a variable. If the child_select is present append it with _ to the base path.

var path = "<?php echo $this->url->link('product/category', 'path=' . $data['category_id']);?>";

window.location.href = child_select ? path + '_' + child_select : path;
//                                  {  If present then append   }

The above statement is equivalent to

if (child_select) {
    window.location.href = "<?php echo $this->url->link('product/category', 'path=' . $data['category_id']);?>_" + child_select;
} else {
    window.location.href = "<?php echo $this->url->link('product/category', 'path=' . $data['category_id']);?>";
}

Upvotes: 3

Manwal
Manwal

Reputation: 23816

Then you can check child_select undefined:

if (typeof child_select != 'undefined')
{
   window.location.href ="<?php echo $this->url->link('product/category', 
'path=' . $data['category_id']);?>_"+child_select;
} else {
   window.location.href ="<?php echo $this->url->link('product/category', 
'path=' . $data['category_id']);?>";
}

Upvotes: 1

Related Questions