[英]how to get dynamic id of dynamically created textbox in jquery
我想通過文本框ID執行keyup事件,並且所有文本框都是通過onclick按鈕事件動態創建的。 為此,我必須使20鍵功能。 如果我使用20鍵功能,那么我的代碼將變得冗長和復雜。 而不是我想對所有文本框使用通用功能。 有人可以建議我怎么做..謝謝
這是我正在解決的問題:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > <a href="#" id="remove_field">Remove</a><input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
請參見下面的代碼片段,以了解如何使此實現更具模塊化和可用性。 訣竅在於思考:我想做什么? 我希望能夠添加多個輸入並添加其值,然后將結果打印在另一個輸入中。
歸結為使用classes
-因為我們將在每一行中使用相同的東西。 然后應用適用於所有類的內容。 沒有任何ID! 您甚至可以使用包含要保存的值的輸入的name
屬性。 在發布時在該屬性中使用[]
甚至可以將您傳遞回漂亮的數組!
我知道這看起來很艱巨,但是刪除我的注釋后,行數將大大減少,並且這種代碼幾乎可以無限擴展和重用。
但是,看看它,它的工作原理很簡單,而且最重要的是-DRY(一旦don't repeat yourself
0,請重新評估,因為應該有更好的方法!)!
您還可以使用<ol>
作為包裝器,然后每次在其中添加<li>
,這樣您就可以自動對前端的盒子進行計數,而無需您的任何努力! 實際上,那太好了,以至於我更改了實現。
var add = $('#add_boxes'); var all = $('#boxes'); var amountOfInputs = 2; var maximumBoxes = 10; add.click(function(event){ // create a limit if($(".box").length >= maximumBoxes){ alert("You cannot have more than 10 boxes!"); return; } var listItem = $('<li class="box"></li>'); // we will add 2 boxes here, but we can modify this in the amountOfBoxes value for(var i = 0; i < amountOfInputs; i++){ listItem.append('<input type="text" class="input" />'); } listItem.append('<input type="text" class="output" name="value" />'); // Lets add a link to remove this group as well, with a removeGroup class listItem.append('<input type="button" value="Remove" class="removeGroup" />') listItem.appendTo(all); }); // This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly. $(document).on("keyup", "input.input", function(event){ // Get the group var group = $(this).parent(); // Get the children (all that arent the .output input) var children = group.children("input:not(.output)"); // Get the input where you want to print the output var output = group.children(".output"); // Set a value var value = 0; // Here we will run through every input and add its value children.each(function(){ // Add the value of every box. If parseInt fails, add 0. value += parseInt(this.value) || 0; }); // Print the output value output.val(value); }); // Lets implement your remove field option by removing the groups parent div on click $(document).on("click", ".removeGroup", function(event){ event.preventDefault(); $(this).parent(".box").remove(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <ol id="boxes"> </ol> <input type="button" value="Add a row" id="add_boxes" />
您可以使用以下簡單功能來定位所有當前或將來的文本框,無論其數量是多少:
$(document).on("keyup", "input[type=text]", function(){ var $textbox = $(this); console.log($textbox.val()); }) $("button").click(function(){ $("#container").append('<input type="text" /><br>'); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <input type="text" /><br> <input type="text" /><br> <input type="text" /><br> </div> <button>Create one more</button>
您不需要復雜的生成ID,也不一定需要一個類(除非您有不想與之沖突的其他input[type=text]
)。 而且您無需復制代碼並編寫相同功能的20倍。 曾經 。 如果要復制代碼,則說明您做錯了。
提供一個代碼段,可能會給您一些提示:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}
您可以為要在其上執行keyup
事件的所有文本框分配一個class
,然后使用class
將事件附加到具有class
元素上。 這是一個例子
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
將keyup
事件附加到具有someClass
類的someClass
。
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
可以與您最喜歡的答案結合的小幫手:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
用法:
uid(); // 1
uid(); // 2
uid(); // 3
將類“ a”和“ b”添加到文本框,將“ box”添加到框中。 然后添加帶有索引的data-idx屬性(未使用!?)。 最后注冊事件處理程序:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
還是一般的:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.