使用jquery在相反(从下到上)的方向附加输入框

时间:2017-01-31 07:13:19

标签: javascript jquery

我想点击添加图标(+)时附加输入框,而如果我们要删除附加的输入框,我们点击删除(X)按钮。但是在这里我希望附加的输入框出现在静态输入框之前,即相反(从下到上)的方向。

Here is the image of what i want to display:

Html:

<div class="input_fields_wrap">
     <input type="text" name="mytext[]">
     <a href="javascript:void(0);" class="add_field_button" title="Add field"><img src="images/plus.png" /></a>
</div>

代码:

  
        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="javascript:void(0);" class="remove_field" title="Remove field"><img src="images/close.png"/></a></div>'); //add input box
            }
        });

        $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });

1 个答案:

答案 0 :(得分:1)

使用.prepend()在点击按钮输入之前添加输入请在下面的代码段中找到更多信息

&#13;
&#13;
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).prepend('<div><input type="text" name="mytext[]"/><a href="javascript:void(0);" class="remove_field" title="Remove field"><img src="images/close.png"/></a></div>'); //add input box
            }
        });

        $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
     <input type="text" name="mytext[]">
     <a href="javascript:void(0);" class="add_field_button" title="Add field"><img src="images/plus.png" /></a>
</div>
&#13;
&#13;
&#13;