mardi 3 avril 2018

How to make a checkbox to append/remove having a default text?

I have a toggle checkbox (see code snippet). When you check it, you can type your name and it will appear below. Uncheck it to remove all.

There is a default text: "You don't have a name".

I need to make the default text appear again when you uncheck the box. How?

             $(function(){
            let NewContent='<div class="added"><p><label>What is your name? </label><input type="text" id="A">                </div></p><p>Your name is: <span class="Y"></span></p>'
            let added = false;
            let $content;
            $(".addremove").on('click', function(){
             /* HERE I REMOVE THE DEFAULT TEXT */
            $(".default").remove();
              /* HOW TO GET IT APPENDED BACK WHEN UNCHECKING THE BOX? */
            if (!added) {
            $content =  $(NewContent).appendTo('.firstappend');
              var name1 = document.getElementById('A');
              name1.addEventListener('input', function() {
               var result = document.querySelector('span.Y');
                console.log(this.value );
                result.innerHTML = this.value;
              });
            }
            else $content.remove();
            $(".default").appendTo(".X");
            added = !added;
          });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
  <input type="checkbox" class="addremove">Do you have a name?</input>
</div>

<div class="X"></div>
<div class="default"><p>You don't have a name</p></div>

<div class="firstappend"></div>



Aucun commentaire:

Enregistrer un commentaire