javascript - 从添加到隐藏字段的值中删除逗号
问题描述
如何用空格替换逗号?我正在使用此代码段将复选框的值添加到隐藏字段。
参考: 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();
});
});
解决方案
而不是这个:
$('#txtValue').val(allVals)
做这个:
$('#txtValue').val(allVals.join(" "))
join
将数组转换为字符串,通过作为参数传递给 的分隔符分隔每个值join
,在本例中为空格。
推荐阅读
- java - Kotlin 和 Gradle 的 Flutter 依赖问题
- powershell - Powershell Here-String 换行符不适用于输出文件
- firebase - 启用持久性的 Firestore 返回不存在的文档 IDS
- python - Tensorflow 中的线程安全图使用
- smalltalk - Pharo 中的方法
- c# - 将基于委托回调的 API 转换为异步
- windows - 没有为服务“Apache”安装 ConfigArgs,使用 Apache 默认值
- javascript - 在 JavaScript 中使用组合
- git - 如何配置 git 从一个存储库中提取并推送到另一个存储库
- c# - 如何在用户控件中使用 ViewModelLocator?