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:
- Enter data for
Test1
andTest2
- Click the checkbox ‘Use actual data’ and enter data for
Test 3
andTest 4
. - Press the button to ‘Clear Element Data for Tests 1 & 2’.
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>
2
Answers
The issue is because you’re clearing the entire content of
#utility-info
, which contains theinput
elements as well as their values.To fix the issue, change your selector to directly target the
input
elements and then useval('')
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 thediv
elements based on the booleanchecked
property of the checkbox.Here’s a working example:
The "best™" might be to actually use declarative HTML that can do all this for you without JS. A
<form>
, and all its inner<input>
elements, can be reset, to their original values, by a<button type="reset">
(or an equivalent<input type="reset">
).Besides being totally clear to AT, and machines what your markup is about, and to work where JS is disabled, it allows you to set an initial value and to reset it back.