Home > Software design >  how to separate buttons in html table
how to separate buttons in html table

Time:12-19

I tried to add buttons at the front of each row, but only the one in the first row would follow my setColor() function.

while(($row=mysqli_fetch_assoc($result))&&($cnt<5)){
          if($row['type']=='0') {
              $cal =$row['kcal'];
              $price =$row['price'];
              if(($cal<=($_SESSION['calorie'])/3)){
                  echo"<tr>
                  <td>
                      <form>
                      <input type='button' value=' ' onclick='setColor()' id='btn'>
                      </form></td>
                      <td>".$row['product']."</td>
                      <td>".$cal."</td>
                      <td>".$price."</td>
                      </tr>";
                  $cnt =1;
              }
          $price=0;
          $cal=0;}
      }

here is the setColor JS function code

<script>
function setColor(){
    var count=1;
    if (count == 0){
        document.getElementById('btn').style.color = "gray";
        count=1;        
    }
    else{
        document.getElementById('btn').style.color = "orange";
        count=0;
    }
    count=0
}

</script>

How can I separate them while keeping the while loop? Thanks.

CodePudding user response:

You need to let the system knows which button you want to change on clicking the button , one of the methods is to use a unique button ID.

Hence simply change to

$index=0;

while(($row=mysqli_fetch_assoc($result))&&($cnt<5)){
          if($row['type']=='0') {
              $cal =$row['kcal'];
              $price =$row['price'];
              if(($cal<=($_SESSION['calorie'])/3)){
                  echo"<tr>
                  <td>
                      <form>
                      <input type='button' value=' ' onclick='setColor(". $index . ")' id='btn". $index . "'>
                      </form></td>
                      <td>".$row['product']."</td>
                      <td>".$cal."</td>
                      <td>".$price."</td>
                      </tr>";
                  $cnt =1;
              }
          $price=0;
          $cal=0;}
$index  ;
      }

and use the following JS

<script>
function setColor(var1){
    var count=1;
    if (count == 0){
        document.getElementById('btn' var1).style.color = "gray";
        count=1;        
    }
    else{
        document.getElementById('btn' var1).style.color = "orange";
        count=0;
    }
    count=0
}

</script>

For the JS code, I do not know what is the purpose of the "count", so you may wish to amend the code to suit your need.

  • Related