2

I'm sure this has been asked befor but I can't seem to find it in a search I have multiple forms on a page generated by php all with onCick event The problem is it only picks up the first event after that any other clicks produce same result from first click Here is javascript

   function CompareScores(form)
    {

var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;

if(scoreA > scoreB){
     alert('Score A is Larger ' + scoreA)
    }else{
     alert('Score B is Larger ' + scoreB)
         }
    }

And the php generating forms

<?php
    while($i<=$numPrelimTeams) {

      if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?>  -->  SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
  <input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
   <input type="hidden" name="game" value="<?php echo $game_num; ?>">
     <p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
        }else{
?>
  <p><u><?php echo $prelimTeam[$i]; ?>  -->  SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
   <input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">

    </form><br><br><br>


<?php
        $game_num++;
        $e=$e+2;
        } 
     $i++;
    }
?>

2 Answers 2

2

Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.

Since you're already sending the form object, use that instead:

var scoreA = form.score_A.value;
...
Sign up to request clarification or add additional context in comments.

Comments

1

There is essentially a single problem with your code. You have multiple instances of the same ID.

To fix it, try something like this.

<input type="text" class="small score_A" name="score_A" size="1" />

Similarly

<input type="text" class="small score_B" name="score_B" size="1" />

Now, you can write a querySelector in your JS

function CompareScores(form) {
    var a = form.querySelector('.score_A').value;
    var b = form.querySelector('.score_B').value;
    //do something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.