首页 > 解决方案 > 从添加到隐藏字段的值中删除逗号

问题描述

如何用空格替换逗号?我正在使用此代码段将复选框的值添加到隐藏字段。

参考: http: //www.dotnetfox.com/articles/jquery-multiple-checkbox-values-to-comma-separated-string-1105.aspx

当前结果如下所示:

<input type="hidden" id="textValue" value="1,2,3,4,5,6,7" />

我想要以下结果

<input type="hidden" id="textValue" value=" 1 2 3 4 5 6 7" />
<div id="mydiv">

        <input type="checkbox" name="swimmingpool" id="swimmingpool" value="1" />

        Swimming Pool<br />

        <input type="checkbox" name="fitnesscenter" id="fitnesscenter" value="2" />

        fitness center<br />

        <input type="checkbox" name="restaurant" id="restaurant" value="3" />

        restaurant<br />

        <input type="checkbox" name="childrenactivities" id="childrenactivities" value="4" />

        children’s activities<br />

        <input type="checkbox" name="complimentarybreakfast " id="complimentarybreakfast"

            value="5" />

        complimentary breakfast<br />

        <input type="checkbox" name="meetingfacilities" id="meetingfacilities" value="6" />

        meeting facilities<br />

        <input type="checkbox" name="petsallowed " id="petsallowed " value="7" />

        pets allowed<br />

        <input type="hidden" id="txtValue">

</div>
jQuery(document).ready(function($){

function updateTextArea() {

            var allVals = [];

            $('#mydiv :checked').each(function () {

                allVals.push($(this).val());

            });

            $('#txtValue').val(allVals)
        }

        $(function () {

            $('#mydiv input').click(updateTextArea);

            updateTextArea();

        });

});

标签: javascriptjqueryinput

解决方案


而不是这个:

$('#txtValue').val(allVals)

做这个:

$('#txtValue').val(allVals.join(" "))

join将数组转换为字符串,通过作为参数传递给 的分隔符分隔每个值join,在本例中为空格。


推荐阅读