简体   繁体   中英

jQuery add one text box inside a td and prevent adding more if click event occured second time inside the same cell

I typed a script which add an input with type=text inside of a clicked td, with the original value of the td inside of it.

$(document).ready(function(){
    $('#med_table').on('click', '.tdSel', function() {
        var num_pills = ($(this).text());
        $(this).val("");
        var id = $(this).closest('tr').attr('id');
        console.log(id);
        $(this).replaceWith('<input type="number" id="test" class="form-control select" value='+num_pills+'>')
        $('#test').on('focusout', function()
        {
            var new_quantity = $(this).val();
            //console.log(new_quantity);
            //alert("out");
            //Ajax
        })
    });
})

My problem is that if I clicked by mistake another time on the same td another text box is added. What I want is to add one single text box on the clicked td .

I tried to set a counter:

$(document).ready(function(){
    var i = 0;
    $('#med_table').on('click', '.tdSel', function() {
        if(i==0)
        {
            var num_pills = ($(this).text());
            $(this).val("");
            var id = $(this).closest('tr').attr('id');
            console.log(id);
            $(this).replaceWith('<input type="number" id="test" class="form-control select" value='+num_pills+'>')
            $('#test').on('focusout', function()
            {
                var new_quantity = $(this).val();
                //console.log(new_quantity);
                //alert("out");
                //Ajax
            })
        }
        i++;
    });
})

It worked but now I can't add text boxes inside other tds .

Try the following code:

HTML:

<table border = "1" width="100%">
  <tr>
    <td>2</td>
    <td>1</td>
    <td>3</td>
  </tr>
</table>

JS:

$(document).ready(function() {
    $("td").on("click", function() {
        var counter = $(this).attr("data-counter");
        if (counter != 1) {
            var data = $(this).text();
            $(this).html('<input type="number" id="test" class="form-control select" value=' + data + '>');
            $(this).attr("data-counter", "1");
        }
    });
});

Try the live demo here

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