我收到了一些HTML复选框的Jquery代码。基本上,选中时,复选框的值将放在输入框中。取消选中该框时,将从输入中清除该值。但是,当您选中多个复选框时,","分隔值。 是否可以通过" - "来分隔价值观?而不是","?我试着玩代码,它只是破坏了代码。我是JS / Jquery的新手,所以如果这是一个简单的答案,我道歉。如果需要,我可以提供更多信息。一个工作的JSFiddle","在这里:https://jsfiddle.net/m240Laka/25/
我的代码位于:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});
答案 0 :(得分:0)
在$ .join()中添加分隔符字符串参数:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
更新:
在$ .split()
中添加相同的内容choiceSelectionsArray = $choiceDisplay.val().split("-")....
答案 1 :(得分:0)
在函数join()
和split()
中,您需要传递所需的分隔符'-'
。我建议您创建一个您使用的局部变量,因此如果需要更容易更改。
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
这是jsfiddle。