Reputation: 3083
I want to clear the contents of all text fields inside a given DIV with a button. I am using this javascript code:
<div id="block1">
<table>
<tr>
<td><!--somefields--></td>
</tr>
<tr>
<td><input type="button" onclick="clear('block1')" value="clear"></td>
</tr>
</table>
</div>
<script type="text/javascript">
function clear(fieldid) {
document.getElementById(fieldid).childNodes[3].innerHTML='';
}
</script>
but its not working. What is wrong?
Thank you.
Upvotes: 1
Views: 4952
Reputation: 12862
You can select all the inputs from needed div
, and set their values empty in a loop.
function clear(fieldid) {
var container = document.getElementById(fieldid);
var inputs = container.getElementsByTagName('input');
for (var index = 0; index < inputs.length; ++index) {
inputs[index].value = '';
}
}
Upvotes: 1
Reputation: 1258
Below piece of code working for you with sample input text box
<div id="block1">
<table>
<tr>
<td><input type="text" value="Hello"/></td>
</tr>
<tr>
<td><input type="button" onclick="clearFields('block1')" value="clear"></td>
</tr>
</table>
</div>
<script type="text/javascript">
function clearFields(fieldid) {
var container, inputs, index;
container = document.getElementById(fieldid);
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
if(inputs[index].type =="text")
inputs[index].value = '';
}
}
</script>
Upvotes: 3