javascript - 按降序添加 html 文本字段 JS

标签 javascript html

添加新文本字段时,我试图使文本字段按降序堆叠。

这是我的代码:

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"> &nbsp; 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排序方法,但没有成功......

提前感谢您的帮助!

最佳答案

您可能搞乱了 idclass,因为 .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"> &nbsp; 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/

相关文章:

html - 表格高度属性似乎没有任何影响

html - CSS 未应用于所有元素

javascript - 如何将 c++ 'int' 转换为 JavaScript?

javascript - 使用 Mootools 获取元素内的特定元素

javascript - 如果满足某些条件,如何在不调用模态的情况下先调用类?

html - 边框和尺寸在 Firefox 中不起作用

javascript - 如何在android中长按获取webview超链接的文本?

javascript - 向下滚动时滚动到一个位置,向上滚动时滚动到另一个位置

javascript - YouTube URL 到 Iframe

javascript - 使用正则表达式进行搜索/替换