简体   繁体   中英

alerts in else statements

Why won't this code work correctly? If someone selects something with an id of of '1599' then an alert will show "$1,599.00". If the id does not match, then the alert should show "$1,499.00". But it doesn't. Could someone help me figure this out?

thanks

<html>
<script type="text/javascript">
function showPrice(){

var a = document.getElementById();

    if (a == "1599"){
        alert("$1,599.00");
    }
    else {
        alert("$1,499.00");
    }
}
<body>
<div class="hc_right">
            <input type="button" class="spc" value="Price" onclick="showPrice()" />
            <p class="price" id="1599">$1,599.00</p>
        </div>

        <div class="hc_right">
            <input type="button" class="spc" value="Price" onclick="showPrice()" />
            <p class="price" id="1499">$1,499.00</p>
        </div>
    </div>

</body>
</html>

You need to let showPrice know which element you want to show the alert for. Right now, you're not actually selecting anything with the document.getElementById ( a will be either null or undefined at this point).

There are a bunch of different ways to go about doing this, but to keep it close to your current implementation, I might do something like this:

HTML

<div class="hc_right">
        <input type="button" class="spc" value="Price" onclick="showPrice(1599)" />
        <p class="price" id="1599">$1,599.00</p>
    </div>

    <div class="hc_right">
        <input type="button" class="spc" value="Price" onclick="showPrice(1499)" />
        <p class="price" id="1499">$1,499.00</p>
    </div>
</div>

Javascript

function showPrice(a){

    if (a == "1599"){
        alert("$1,599.00");
    }
    else {
        alert("$1,499.00");
    }
    return false;
}

Fiddle here

I think you will see the issue if you add an alert(a); before the if(...) -- My guess is that you aren't getting the value you expect in there.

The document.getElementById() method takes a parameter of the ID to look for. Something like:

document.getElementById("1599")

and will return the document element that has that ID. Not sure what it will return when no parameter is passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM