zac1987
zac1987

Reputation: 2777

javascript if else statement problem

<?php $genderdb = "Male"?>
<script type="text/javascript">
        var genderdb = "<?php echo $genderdb; ?>";
        if ((genderdb == "Female") || ($genderdb == "Shemale")) {
            var himher = "her";
        } else {
            var himher = "him";
        }
        alert (himher);
</script>

If I change php $genderdb = "Female", then it can alert the value successful. But if $genderdb = "Male", the page won't have alert. Why? Where is the error?

Upvotes: -1

Views: 1569

Answers (3)

Town
Town

Reputation: 14906

Remove the $ from your 'shemale' comparison.

That's causing your script to fail as it's looking for a non-existent variable.

        var genderdb = "<?php echo $genderdb; ?>";
        if ((genderdb == "Female") || (genderdb == "Shemale")) {
            var himher = "her";
        } else {
            var himher = "him";
        }
        alert (himher);

Upvotes: 0

Wayne
Wayne

Reputation: 60414

You have an error in this line:

if ((genderdb == "Female") || ($genderdb == "Shemale")) {

Namely, the second reference to genderdb uses the name of the PHP variable, instead of the JavaScript variable.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

if ((genderdb == "Female") || ($genderdb == "Shemale")) {

should be

if ((genderdb == "Female") || (genderdb == "Shemale")) {

It works when genderdb is "Female", because then the (broken) second comparison doesn't come into the equation.

In addition, using var inside the conditional blocks is suspect. Javascript actually doesn't have block scope so it works, but it's something to consider.

Upvotes: 4

Related Questions