how do I clear the previously populated text from the checkbox when I uncheck the box?
the list below codes is when you check a box and populated text in the text area.
$('input:checkbox').click(function(){
var tb = "#" $(this).attr('rel');
if($(this).is(":checked"))
$(tb).append(this.name "\n");
else($(tb)).removeAttr(":checked");
})
CodePudding user response:
You can use the replace()
function to remove the name from the text field.
$('input:checkbox').click(function() {
var tb = "#" $(this).attr('rel');
let text_to_add = this.name "\n";
if ($(this).is(":checked")) {
$(tb).append(text_to_add);
} else {
let remove = this.name "\n";
$(tb).text(function(i, text) {
return text.replace(text_to_add, '');
});
}
})
CodePudding user response:
The following script assembles the checked checkboxes' name
attribute values and places them into the textbox that is addressed by the checkbox's rel
attribute:
$('input:checkbox').click(function(){
var tb = $(this).attr('rel');
$("#" tb).val($("[rel=" tb "]:checked").map((i,e)=>e.name).get().join("\n"))
})
textarea {height:50px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input name="one" type="checkbox" rel="mytext">one</label>
<label><input name="two" type="checkbox" rel="mytext">two</label>
<label><input name="three" type="checkbox" rel="mytext">three</label><br>
<textarea id="mytext"></textarea>
<br>
<label><input name="four" type="checkbox" rel="text2">4</label>
<label><input name="five" type="checkbox" rel="text2">5</label>
<label><input name="six" type="checkbox" rel="text2">6</label><br>
<textarea id="text2"></textarea>