mick
mick

Reputation: 1

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>

Upvotes: 0

Views: 110

Answers (3)

Demian Brecht
Demian Brecht

Reputation: 21368

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

Upvotes: 1

MikeTheReader
MikeTheReader

Reputation: 4190

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.

Upvotes: 0

jcov
jcov

Reputation: 222

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.

Upvotes: 0

Related Questions