gpt4 book ai didi

javascript - 获取动态文本字段的目标id

转载 作者:行者123 更新时间:2023-12-03 06:22:54 24 4
gpt4 key购买 nike

我有一个按钮,单击该按钮即可添加动态列。我试图获取每列的目标 id。

<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>

js

$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
alert("target id" + e.target.id); // I get nothing here
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

如何获取目标 ID,以及如果它具有某些值,我也想在删除添加的动态列之前打印该值?

最佳答案

var max_fields = 10,
wrapper = $('.input_fields_wrap'),
add_button = $('.add_field_button'),
x = 1;

$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input id="' + x + '" type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>');
}
});

$(wrapper).on('click', '.remove_field', function(e) {
var div = $(this).parent('div'),
input = div.find('input');
e.preventDefault();

console.log('target id:', input.attr('id'));
console.log('target value:', input.val());

div.remove();
x--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>

关于javascript - 获取动态文本字段的目标id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38787802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com