I’m trying to make a button to clear an input next to it. So far my code is like this,
<input type="file" name="lay4img1" id="lay4img1">
<a href="javascript:;"
onclick="
if(document.getElementById('lay4img1').value != '') {
document.getElementById('lay4img1').value = '';
alert('clear success');
} else {
alert('failed');
}">
<input type="button" value="Clear">
</a>
When I choose a file and make lay4img1 have value, and then push the button, the alert clear success is executed so document.getElementById is also executed, but the field is still not empty? What’s wrong from my code?
Other than <input type="file" name="lay4img1" id="lay4img1">, I still have other fields so I don’t want and can’t use <button type="reset"> for it will clear the whole form, which I consider as not user friendly.
That is a horrible way of binding handlers. Additionally, wrapping a button with an anchor is completely pointless. Consider using JS to add an event listener. This listener removes the old input and replaces it with a new one:
HTML:
JS:
Here is a demonstration: http://jsfiddle.net/LHM9V/1/