添加新文本字段时,我试图使文本字段按降序堆叠。
这是我的代码:
JS:
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" class="form-control" name="mytext[]" placeholder="<Menu Name / Transaction ID/ Description>"/> <select><option ></option><option >Add</option></select><a href="#" class="remove_field"> Delete</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
我尝试使用js排序方法,但没有成功......
提前感谢您的帮助!
最佳答案
您可能搞乱了 id
和 class
,因为 .XXX
表示具有类 XXX
的元素,而 id 为 YYY
的元素应使用选择器 #YYY
。
您可以将 .add_field_button
更改为 #add_field_button
或将 ID 为 add_field_button
的按钮更改为具有类 add_field_button
code> 正如我在代码片段中所做的那样。
如果您想降序,请使用 .prepend()因此最新添加的文本框将插入到容器的前面。
$(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button CLASS
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).prepend('<div><input type="text" class="form-control" name="mytext[]" placeholder="<Menu Name / Transaction ID/ Description>"/> <select><option ></option><option >Add</option></select><a href="#" class="remove_field"> Delete</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="add_field_button">Test</button>
<div class="input_fields_wrap"></div>
关于javascript - 按降序添加 html 文本字段 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31748898/