A
A
Alekosh Akhosh2021-06-05 14:17:35
JavaScript
Alekosh Akhosh, 2021-06-05 14:17:35

How to solve a problem with three elements?

I can't solve a simple problem.

The task is: Given a checkbox, a button and a paragraph. When the button is pressed, if the checkbox is checked, output the word 'hello' in the paragraph, and if the checkbox is not checked, then the word 'bye'
. But somewhere he made a mistake. I can be sure that the error is inside IF, as I wrote it incorrectly. And it is quite likely near the name of the func function, due to the fact that the function was made not secretive / anonymous. My head is in a fog, I can't decide

ps yes, and maybe the second innerHTML line is superfluous, no need

<input type="checkbox" id="elem">
<input type="submit" id="btn">
<p id="p">text...</p>


let elem = document.querySelector('#elem')
let btn = document.querySelector('#btn')
let p = document.querySelector('#p')

    btn.addEventListener('click', func());
    elem = false;
     
    function func(){
        if(elem.checked = true){
            p.innerHTML =+ p.innerHTML + 'Привет'
        }
    }
    console.log(elem);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-06-05
@Akhosh

  1. remove it elem = false;- the variable contains the element with which to work
  2. assign an event listener - it's just there funcwithout parentheses. Otherwise, it will listen to the result of the function call
  3. elem.checked == true- it must be exactly ==. You have one equals sign, it assigns a value.

spoiler
const elem = document.getElementById('elem');
const btn = document.getElementById('btn');
const p = document.getElementById('p');

btn.addEventListener('click', () => p.innerText = elem.checked ? 'Привет' : 'Пока!');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question