[英]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. 我输入一个脚本,添加一个
input
与type=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");
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.