JavaScript conditional ignoring IF Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JavaScript conditional ignoring IF without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a conditional statement set on the url,I tested both the IF and ELSE and it does work with a simple document.write. However, I am trying to output Php i the conditional but it just always outputs the else statement, Php is not my strongest language:

<script type="text/javascript">

if(
window.location.href=="mywebsite.com"
)
{

    document.write('<label for="qty"><?php echo $this->__("Qty:") ?></label><input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__("Qty") ?>" class="input-text qty" />')

}else{

    document.write('<label for="qty"><?php echo $this->__(' ') ?></label>
        <input type="hidden" name="qty" id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product) ?>" title="<?php echo $this->__("Qty") ?>" class="input-text qty" />')

}

</script>

Answer

window.location.href contains the full URL. If you just want to check the hostname part of the URL, use window.location.host.

if (window.location.host == "mywebsite.com") {
    ...
}

Another option would be to do all the work on the server.

<?php
if ($_SERVER['SERVER_NAME'] == 'mywebsite.com') {
?>
<label for="qty"><?php echo $this->__("Qty:") ?></label>
    <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__("Qty") ?>" class="input-text qty" />
<?php } else {
?>
<label for="qty"><?php echo $this->__(' ') ?></label>
    <input type="hidden" name="qty" id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product) ?>" title="<?php echo $this->__("Qty") ?>" class="input-text qty" />
<?php }
We are here to answer your question about JavaScript conditional ignoring IF - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji