简体   繁体   中英

Why does the value of input field return undefined

I was working on a way to change content of the page.

I run the script. I am able to change the text once by double clicking on the paragraph but second time it returns undefined.

 $(document).ready(function(){ $(".editable").dblclick(function(){ var id = $("this p").attr('id'); $(this).html("<input id="+id+" type='text'>"); $(this).keyup(function(event){ if (event.which == 13){ //alert(id); var valT = document.getElementById(id).value; $(this).html("<p id='"+id+"'>" + valT + "</p>"); } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="editable" ondblclick=""> <p id="asd">first Paragraph</p> </div> 

I found two problems in your code. Firstly, the selector of the id and secondly, the keyup event gets made every time you click. The code below will unset the keyup event before creating a new one.

https://jsfiddle.net/24kjchxj/

$(document).ready(function(){
  $(".editable").dblclick(function(){
    var id = $(this).find("p").attr('id');
    $(this).html("<input id="+id+" type='text'>");
    $(this).off('keyup');
    $(this).keyup(function(event){
      if (event.which == 13){
        //alert(id);
        var valT = document.getElementById(id).value;
        $(this).html("<p id='"+id+"'>" + valT + "</p>");
      }
    });
  });
});

Problem with your code is that whenever your double click event trigger, it register new onkeyup event. Try to replace your code with the following one:

  $(document).ready(function(){
                var id;
                $(".editable").dblclick(function(){
                  id  = $(this).find('p').attr('id');
                    $(this).html("<input id="+id+" type='text'>");

                });

                $("body").on("keyup", ".editable input", function(event){

                    if (event.which == 13){
                      var valT = document.getElementById(id).value;
                      $(".editable").html("<p id='"+id+"'>" + valT + "</p>");
                    }
                });

            });

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