Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to Javascript and I've only recently learned HTML and CSS. So, example, in this example;
  <body>
    <p>Player 1: Chris</p>

    <script>
      var para = document.querySelector('p');
      para.addEventListener('click', updateName);
      function updateName() {
        var name = prompt('Enter a new name');
        para.textContent = 'Player 1: ' + name;
      }
    </script>

The given Javascript can only change "Player 1: Chris". If I have to add "Player 2: Adam" the same script doesn't work. What modifications do I have to use?


What I have tried:

<body>
   <p>Player 1: Chris</p>

   <script>
     var para = document.querySelector('p');
     para.addEventListener('click', updateName);
     function updateName() {
       var name = prompt('Enter a new name');
       para.textContent = 'Player 1: ' + name;
     }
   </script>
Posted
Updated 8-Feb-18 8:59am

You need to add ID's to the elemnts and select accordingly
HTML
<p id="p1">Player 1: Chris</p>
  <p id="p2">Player 2: Fred</p>
JavaScript
<script>
 var p1 = document.getElementById("p1");
 var p2 = document.getElementById("p2");
 p1.addEventListener('click', updateName1);
 p2.addEventListener('click', updateName2);
      function updateName1() {
        var name = prompt('Enter a new name');
        p1.textContent  = 'Player 1: ' + name;
      }	
      function updateName2() {
        var name = prompt('Enter a new name');
        p2.textContent  = 'Player 2: ' + name;
      }	
</script>
I'm sure with a little ingenuity you could combine the two listener functions into one and pass a variable....
 
Share this answer
 
The event handler will be passed an event object, which exposes the currentTarget[^] property representing the element which raised the event.

The only problem is knowing which label to display in front of the name. But you can get around that by using another element to hold the name:
HTML
<p class="player">Player 1: <span class="name">Chris</span></p>
<p class="player">Player 2: <span class="name">Fred</span></p>
JavaScript
var para = document.querySelectorAll('p.player');
for (var i = 0; i < para.length; i++){
    para[i].addEventListener('click', updateName);
}

function updateName(e) {
    var p = e.currentTarget;
    var label = p.querySelector('span.name');
    var name = label.innerText;
    name = prompt('Enter a new name', name);
    if (name) {
        label.innerText = name;
    }
}
Demo[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900