0

Why the function give me the same value when I want it to change every time I choose other radio buttom

    <form>
    <input type="radio" id="male" name="gender" value="male">
    <label for="male">Male</label><br>
    <input type="radio" id="female" name="gender" value="female">
    <label for="female">Female</label><br>
    <input type="radio" id="other" name="gender" value="other">
    <label for="other">Other</label>
    <button onclick="addSpan()">Try it</button>

</form>

this is function

<script>
function addSpan() {
    var female = document.getElementById("female");
    var male = document.getElementById("male");
    var other = document.getElementById("other");
    if (document.getElementById("female").checked = true) {
        document.body.innerHTML += '<span class="bullet">female</span> ';
    }
    else if (document.getElementById("male").checked = true) {
        document.body.innerHTML += '<span class="bullet">male</span> ';
    }
    else {
        document.body.innerHTML += '<span class="bullet">other</span> ';
    }
}
resultat [enter image description here][1]

2 Answers2

1

Used = inplace of ===

function addSpan() {
    var female = document.getElementById("female");
    var male = document.getElementById("male");
    var other = document.getElementById("other");
    if (female.checked === true) { // when checking something is true/false use === not = as = assigns a new value and === is checking if it is equal, also use the variables you assigned at the start
        document.body.innerHTML += '<span class="bullet">female</span> ';
    }
    else if (male.checked) { // You can actually shorthand this as an IF statement automatically checks for if its equal to true
        document.body.innerHTML += '<span class="bullet">male</span> ';
    }
    else {
        document.body.innerHTML += '<span class="bullet">other</span> ';
    }
}
Coupe
  • 372
  • 2
  • 12
1

You want == instead of = here:

document.getElementById("female").checked == true

= makes it true. == asks if it is true.

Ben West
  • 4,398
  • 1
  • 16
  • 16