How to change code depending on a clicked button

Viewed 191

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?

4 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>

You can do it like this;

In the HTML pass the gender value in to the function;

<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>

In the js function;

function calculate(val){
let genderMultiplier = val * 100;

return genderMultiplier;
};

I think you can use name-value pairs.

Such as:

<button class="gender-button" name="male" value="0.55" onclick="calculate(this.value)">MALE</button>

<button class="gender-button" name="female" value="0.68" onclick="calculate(this.value)">FEMALE</button>

Then, handling the value from buttons by calling onclick.

<script>
   function calculate(genderMultipiler){
       let result = genderMultipiler * 100;
       return result;
   };
</script>

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>
Related