简体   繁体   中英

How to change html text to value of button when clicked?

Just a question that's been bugging me about my code, which is this:

My Code: The user creates a button (working) When that button is clicked, jQuery gets the value of that button and displays it on the page in a paragraph text (partially working)

Problem: When the buttons that were created by me, as testers, in the original code are clicked, this works. However, newly created buttons by the user do not change the paragraph text text.

HTML test buttons code:

        <button id="1" class="createdGroupsButton">TEST1</button>
        <button id="2" class="createdGroupsButton">TEST2</button>
        <button id="3" class="createdGroupsButton">TEST3</button>

jQuery onClick function for buttons:

      $(".createdGroupsButton").on('click', function(event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        let id = (event.target.id);
        let name = document.getElementById(id).innerHTML;
        document.getElementById("currentGroup").innerHTML = name;
      });

jQuery that creates buttons made by the user:

let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);

userInput is a previously created variable that takes the value from a text box which the user types in.

Code So Far: CodePen snippet

Try with delegation approach which will attach the events to the elements that are added to the document at a later time .

Change:

$(".createdGroupsButton").on('click', function(event) {

To:

$('body').on('click', '.createdGroupsButton', function(event) {

Demo:

 $('body').on('click', '.createdGroupsButton', function(event) { event.stopPropagation(); event.stopImmediatePropagation(); let id = (event.target.id); let name = document.getElementById(id).innerHTML; document.getElementById("currentGroup").innerHTML = name; }); let userInput = 'ANOTHER'; let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`); $('body').append(newGroup);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="1" class="createdGroupsButton">TEST1</button> <button id="2" class="createdGroupsButton">TEST2</button> <button id="3" class="createdGroupsButton">TEST3</button> <div id="currentGroup"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM