0

Trying to display text in a <p> when checkbox is checked from input modal.

var mayo1 = document.getElementById('mayo1').checked;

if (mayo1.checked == true){
            document.getElementById('order1mayo').innerHTML = "Mayo";
 } 
<input type="checkbox" id="mayo1" value="Mayo"> Mayo
<p id="order1mayo"></p>

    
Chris W.
  • 22,835
  • 3
  • 60
  • 94
Jeffrey
  • 1
  • 4

5 Answers5

0

The input field checked property gets true or false. So your mayo1 variablee can be a true or false boolean type. In this case if (mayo1.checked == true) is a mistake. The correct condition is if(mayo1) { ...}

miciry89
  • 196
  • 1
  • 5
0

The problem happens because your code

if (mayo1.checked == true){
            document.getElementById('order1mayo').innerHTML = "Mayo";
 } 

executes only one time immediately after start. You checkbox is not checked at that moment and thus nothing happens.

You have to watch for the changes using eventListener and change the text content depending on current checkbox status. See this example for the details.

Sergey Mell
  • 7,780
  • 1
  • 26
  • 50
0

You need to actually handle an event and go from there;

isChecked = (i) => {
    const o = document.getElementById("order1mayo");
    i === true ?
      o.innerHTML = "Mayo":
      o.innerHTML = "NO Mayo";
}
<input type="checkbox" 
       id="mayo1" 
       value="Mayo" 
       onchange="isChecked(this.checked)">Mayo
       
<h4 id="order1mayo"></h4>
Chris W.
  • 22,835
  • 3
  • 60
  • 94
0

Your mayo1 var is true or false depend on your checkbox, so mayo1.checked is wrong expression...

Try this instead...

if (mayo1) {
  document.getElementById('order1mayo').innerHTML = "Mayo";
}
Rastalamm
  • 1,712
  • 3
  • 23
  • 32
Maor Barel
  • 37
  • 6
0

You're trying to see if mayo1.checked.checked is true - use only one checked:\

var mayo1 = document.getElementById("mayo1").checked;
if (mayo1) {
    document.getElementById("order1mayo").innerHTML = "Mayo";
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79