简体   繁体   English

jQuery在td内添加一个文本框,如果第二次在同一单元格内发生click事件,则阻止添加更多文本框

[英]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. 我输入一个脚本,添加一个inputtype=text被点击的TD内,与原值td在它的内部。

$(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. 我的问题是,如果我再次错误地单击同一td则会添加另一个文本框。 What I want is to add one single text box on the clicked td . 我想要的是在单击的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 . 它起作用了,但是现在我不能在其他tds添加文本框。

Try the following code: 尝试以下代码:

HTML: HTML:

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

JS: 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 这里尝试现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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