I'm trying to clear the data that's in each child element of a parent element without removing (or hiding) the actual child elements.
To reproduce the problem:
Test1
and Test2
Test 3
and Test 4
.This is intended to remove the innerHTML
data, not the elements itself.
I want the elements to remain visible and usable, just empty of any data. I only want the data to be cleared.
How can I do this?
$(function() {
$("#actual").click(function() {
if ($("#actual").is(":checked")) {
$("#utility-info").hide();
$("#actual-utils").show();
} else {
$("#utility-info").show();
$("#actual-utils").hide();
}
});
$("#clear-values").click(function() {
$("#utility-info").html('');
});
});
#actual-utils {
display: none;
}
span {
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="actual" name="actual-util-info"> Use actual data
<div> </div>
<div id="energy-info">
<div id="utility-info">
<div>Test 1 <input id="test1" type="number" name="test1"></div>
<div>Test 2 <input id="test2" type="number" name="test2"></div>
</div>
<div id="actual-utils">
<div>Test 3 <input id="actual1" type="number" name="actual1"></div>
<div>Test 4 <input id="actual2" type="number" name="actual2"></div>
</div>
<div> </div>
<button id="clear-values">Clear Element Data for Tests 1 & 2</button>
</div>
The issue is because you're clearing the entire content of #utility-info
, which contains the input
elements as well as their values.
To fix the issue, change your selector to directly target the input
elements and then use val('')
to clear the values.
Also note that you can improve the logic and make it more succinct by caching the jQuery objects you create when making the calls to the DOM, and by using the toggle()
method to hide/show the div
elements based on the boolean checked
property of the checkbox.
Here's a working example:
jQuery($ => {
const $utilityInfo = $('#utility-info');
const $actualUtils = $('#actual-utils');
$('#actual').on('click', e => {
const useActual = e.target.checked;
$utilityInfo.toggle(!useActual);
$actualUtils.toggle(useActual);
});
$('#clear-values').click(function() {
$utilityInfo.find('input').val('');
});
});
#actual-utils {
display: none;
}
span {
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="actual" name="actual-util-info"> Use actual data
<div> </div>
<div id="energy-info">
<div id="utility-info">
<div>Test 1 <input id="test1" type="number" name="test1"></div>
<div>Test 2 <input id="test2" type="number" name="test2"></div>
</div>
<div id="actual-utils">
<div>Test 3 <input id="actual1" type="number" name="actual1"></div>
<div>Test 4 <input id="actual2" type="number" name="actual2"></div>
</div>
<div> </div>
<button id="clear-values">Clear Element Data for Tests 1 & 2</button>
</div>