从字符串jquery中删除特定字符



好的,所以虽然它看起来是正常的子字符串或替换了解决方案答案,但对我来说相当复杂。

我有3个checkboxesA、 B、C和一个文本框现在,当用户选择任何复选框时,复选框的值都会附加到文本框中,即他第一次选择A->文本框将附加A然后,如果选择B->文本框的值将是A、B,依此类推

我已经做了。现在的问题是取消检查。

如果textbox的值为A、B、C,即所选复选框为A、B、C,并且如果用户取消选择B,则该值应为A、C,然后再次取消选择C,则该数值应为A。

我尝试了多种方法,但并非适用于所有条件,有时会变成A、C或A、B

有什么解决方案吗?提前感谢:(

您可以简单地在更改框时重新创建列表

let els = [...document.getElementsByClassName('check')];
els.forEach(e => e.addEventListener('change', () => {
document.getElementById('foo').value = els.filter(x => x.checked).map(x => x.value).join();
}))
.flex {
display: flex;
flex-direction: column;
}
<div class="flex">
<input id="foo" />
<label><input type="checkbox" class="check" value="A"/>A</label>
<label><input type="checkbox" class="check" value="B"/>B</label>
<label><input type="checkbox" class="check" value="C"/>C</label>
</div>

试试这个:

1( 在每个复选框上单击/取消单击获取所有选中复选框的值。(例如[A','B'](

2( 生成带有联接值的新字符串。[A','B'].join(','(//返回'A,B'

3( 用新字符串设置文本框

如果您需要代码,您可以提交当前代码。

这是我在不知道如何跟踪检查内容的情况下提出的,这是一种数据驱动的方法。

var checked = [];
function updateValue() {
$('#selected').val(checked.toString());
}
$('[type=checkbox]').click(function(e) {
var value = e.target.value;
if(e.target.checked) {
checked.push(value);
} else {
checked.splice(checked.indexOf(value), 1);
}
updateValue();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="A">A<br>
<input type="checkbox" value="B">B<br>
<input type="checkbox" value="C">C<br>
<input type="text" id="selected">

$(function() {

const valArray = [];	// our value array here what gonna show in textarea
	
/**
- on change check if checkbox checked or not
- if checked push value of checkbox to array
if not search in our array "valArray" and get it's index then remove it
- change textarea value with the new array "valArray"
*/
$('.checkboxes input').on('change', function(e) {
const $thisVal = $(this).val(),
	  isChecked = $(this).is(':checked');
if (isChecked) {
valArray.push($thisVal);	
} else {
const searchOnThisVal = valArray.find(item => $thisVal === item),
	    getTheIdx = valArray.indexOf(searchOnThisVal);
valArray.splice(getTheIdx, 1);
}
		
$('.textarea').empty();
$('.textarea').text(valArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
<label>
		<input type="checkbox" value="a">
		the checkbox A.
	</label>
	<label>
		<input type="checkbox" value="b">
		the checkbox B.
	</label>
	<label>
		<input type="checkbox" value="c">
		the checkbox C.
	</label>
</div>
<textarea class="textarea" placeholder="your choice..."></textarea>

这应该在使用jQueryAPI的情况下起作用