Home > database >  add() doesn't get called by onClick
add() doesn't get called by onClick

Time:03-09

I'm trying to update the number of participants by increasing it by one every time the submit button gets clicked, and by doing so I added an add() inside my script tag and increased the participant number every time it gets clicked. But the number of participants doesn't get changed for some reason.

Btw I'm new to DOM and JS

 <h5>Number of participant:<span id="submit">0</span></h5>
    <button type="button" onclick="add()">Submit</button>
</div>
<script>
    let Agenda_style = document.querySelector('.agenda'); //to add style  you must acess the class name/ID using querySelector
    Agenda_style.style.color = "red "; // set color to red to change the color of the class agenda
    let NewElement = document.createElement("li "); //create new element of type <li>
    NewElement.innerText = "Here "; // add a text inside the <li> element 
    Agenda_style.append(NewElement); // append a tet to the agendaa class

    let participant = 0;

    function add() {
        participant  ;
        document.getElementById("submit").innerText = participant;
    };
</script>

CodePudding user response:

It fails for me, as I have now .agenda element.. do you have that in your HTML?

If I comment out that section of the script, the remaining piece works.

<h5>Number of participants: <span id="submit">0</span></h5>
    <button type="button" onclick="add()">Submit</button>
</div>
<script>
    /*let Agenda_style = document.querySelector('.agenda'); //to add style  you must acess the class name/ID using querySelector
    Agenda_style.style.color = "red "; // set color to red to change the color of the class agenda
    let NewElement = document.createElement("li "); //create new element of type <li>
    NewElement.innerText = "Here "; // add a text inside the <li> element 
    Agenda_style.append(NewElement); // append a tet to the agendaa class*/

    let participant = 0;

    function add() {
        participant  ;
        document.getElementById("submit").innerText = participant;
    }
</script>

CodePudding user response:

These days we tend to not use inline JavaScript, so it would be best to grab your button with querySelector, and then use addEventListener to call your function when it's clicked. This way there's a "separation of concerns" between your mark-up, your CSS, and your code.

const number = document.querySelector('#number');
const button = document.querySelector('button');

button.addEventListener('click', add, false);

let participant = 0;

function add() {
  number.textContent =   participant;
}
<h5>Number of participant:
  <span id="number">0</span>
</h5>

<button type="button">Submit</button>

CodePudding user response:

This should be working

function add() {
  let val = document.querySelector('#submit').innerText;
  val = parseInt(val) 1;
}
  • Related