Reputation: 1121
I would like to append some text to a <span>
after checking whether or not a checkbox has been checked. I have multiple checkboxes on the page and I only want to append the <span>
once. All the solutions I have seen don't seem to work for me. I have tried to check by:
if ($('input:checkbox[name="skills"]').prop('checked')) {
$('#filter-7').append($('#headingSkills a').text());
}
And:
if ($('input:checkbox[name="skills"]').is(':checked')) {
$('#filter-7').append($('#headingSkills a').text());
}
Neither seem to work and I don't want to add the append() to my change function because it appends the span multiple times and I only want it to be appended when the checkbox is checked once.
Here is my change function:
$('input:checkbox[name="skills"]').change(function () {
var values = $('input:checkbox[name="skills"]:checked').map(function () {
return '<span><button class="remove-selection" value="' + this.value.trim() + '"></button> ' + this.value.trim() + '</span>';
}).get();
$('#filter-7').append($('#headingSkills a').text());
$('#filter-7-result').empty().append(values);
});
Here is my HTML:
<h4 class="panel-title">
<a role="button" id="button-7" data-toggle="collapse" data-parent="#accordion" href="#skillsCollapse"
aria-expanded="true" aria-controls="skillsCollapse">
Skills
</a>
</h4>
<label>
<input type="checkbox" name="skills" value="Accounting">Accounting</label>
<label>
<input type="checkbox" name="skills" value="Administration">Administration</label>
<label>
<input type="checkbox" name="skills" value="Budgeting">Budgeting</label>
<label>
When someone clicks on one of the checkboxes above, I want to append the button title (Skills) to:
<span id="filter-7"></span>
I know this a commonly asked question but nothing I have tried seems to work.
Upvotes: 1
Views: 648
Reputation: 337714
The issue is because you're appending the text node every time this logic runs. If you only want the value to be shown once as each value is selected use text()
instead of append()
:
$('#filter-7').text($('#headingSkills a').text());
Upvotes: 1
Reputation: 1636
Use is(':checked')
for checking if checkbox is checked
$('.check').change(function(e){
var text='';
$('.check').each(function(e){
if($(this).is(':checked'))
text='checked';
})
$('.content').html(text)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="content"></span>
<input type="checkbox" class="check">one
<input type="checkbox" class="check">two
<input type="checkbox" class="check">three
<input type="checkbox" class="check">Four
Upvotes: 0