Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change code depending on a clicked button

I have two buttons defined in HTML, [Male] and [Female].

<div class="gender-buttons" id="gender-buttons">
   <button class="male-button">MALE</button>
   <button class="female-button">FEMALE</button>
</div>

I want the values of the buttons to be set as below

  • [Male] = 0.55
  • [Female] = 0.68

The user will click which gender they are then will start a function.

<script>
  function calculate(){
    const genderMultiplier = document.getElementById("gender-buttons");
    return genderMultiplier * 100;
  };
</script>

How do I connect my HTML to JavaScript so that when the user clicks male, the function will use 0.55 in the function and vice versa with female?

like image 293
Mo Miah Avatar asked Mar 20 '26 13:03

Mo Miah


2 Answers

Have you tried using onClick event and the value property for the buttons?

function calculate(target){
   var genderVal = target.value * 100
   console.log(genderVal) // for your information - can remove
   return genderVal
}
<div class="gender-buttons" id="gender-buttons">
   <button class="male-button" value=0.55 onClick="calculate(this)">MALE</button>
   <button class="female-button" value=0.68 onClick="calculate(this)">FEMALE</button>
</div>
like image 181
lbragile Avatar answered Mar 23 '26 03:03

lbragile


add an onclick event in the button, use the value to calculate...

<div class="gender-buttons" id="gender-buttons">
   <button class="male-button" onclick="calculate(0.55)">MALE</button>
   <button class="female-button" onclick="calculate(0.68)">FEMALE</button>
</div>

<script>
    function calculate(genderMultiplier){
        genderMultiplier * 100;
        return genderMultiplier; //use this variable where ever you want.
    }
</script>
like image 29
Merrin K Avatar answered Mar 23 '26 04:03

Merrin K