简体   繁体   English

将字符串数组传递给输入jquery的value属性

[英]passing array of strings to value attribute of input jquery

I have this input tag with id="clientAdd" when user write on it and click enter the written can be added in div as a tag and all tags are saved as array of strings I want to pass this array to the value of the hidden input tag id="clientAddCode" 当用户在其上输入内容时,我使用id =“ clientAdd”输入标签,然后单击输入,可以将div作为标签添加到div中,并且所有标签都保存为字符串数组,我希望将此数组传递给hidden的值输入标签id =“ clientAddCode”

<input type="text" id="clientAdd" value="" class="form-control required">
<input type="hidden" id="clientAddCode" name="address">

I try to pass the array of strings as it to the value of the hidden input tag id="clientAddCode" but it always gives me empty value. 我尝试将字符串数组传递给隐藏的输入标签id =“ clientAddCode”的值,但它总是给我空值。

var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
     $(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
        stringList.push(this.value);
        this.value = "";
        $(document).on("click", ".removeAddress", function() {
            var removeItem = $(this).parent().clone().children().remove().end().text();
            stringList = $('.removeAddress').map(function(){
              return $(this).parent().clone().children().remove().end().text()
            }).get()
            $(this).parent().remove();
            $("#clientAddCode").val(stringList);
            console.log(stringList);
        });
     }
});

You should convert the array in a single string, you could do this using the join function: 您应该将数组转换为单个字符串,可以使用join函数执行此操作:

The join() method joins the elements of an array into a string, and returns the string. join()方法将数组的元素连接到字符串中,然后返回该字符串。

array.join(separator) array.join(隔膜)

separator Optional . 分隔符可选 The separator to be used. 要使用的分隔符。 If omitted, the elements are separated with a comma 如果省略,则元素之间用逗号分隔

See following please: 请参阅以下内容:

 var arr = ["test1", "test2", "test3"]; var stringList = arr.join(", "); console.log(stringList); //Write in a div $("#clientAddCode").html(stringList); //Write in a text $("#myList").val(stringList); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="clientAddCode"></div> <input id="myList" type="text" /> 

In the above example, I've concatenated all the items with a comma. 在上面的示例中,我用逗号将所有项目连接在一起。 I hope it helps you, bye. 希望对您有帮助,再见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM