简体   繁体   中英

How to show the variable in a input field using jquery?

I have a table and i want to update the values of the table cell on click . I want to show an input field containing current value . Current value is showing but when i click on input filed to edit then suddenly the input field become empty .

$('td#11').click(function(event){
 var valuee = $('td#11').text();
 $('td#11').html("<form method='post'><input style='color:black;' value=" +valuee+ "></form>");

});

An alternative other solutions:

$('td#11').click(function(event){
if($('td#11').find('form, input').length == 0) { 
    var valuee = $('td#11').text();
    $('td#11').html("<form method='post'><input id='txt11' style='color:black;' value=" +valuee+ "></form>");
}
});

You can add another snippet with above snippet to remove text-box on losing focus to it as below:

$(document).on('blur', 'input#txt11', function() {
    $('td#11').html($('input#txt11').val());
}); 

Working demo jsFiddle

The problem is that your click event fires again and again and so on.

To avoíd this, use event.target.tagName And check if it does not match "INPUT"

$('td#11').click(function(event) {
  if (event.target.tagName != "INPUT") {

    var valuee = $('td#11').text();
    $('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>");

  }
});

Working Demo below

 $('td#11').click(function(event) { if (event.target.tagName != "INPUT") { var valuee = $('td#11').text(); $('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td id="11">text</td> </tr> </table> 

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