Changing the content of an input via a button

Asked

Viewed 38 times

1

I am a beginner in programming and I am developing a mini calculator project in order to study. I decided to implement a erase button to clean the display, but I can’t make it work at all.

HTML part of the display

        <div class="visor">
            <input type="text" name="display" id="display">
            <input type="button" value="C" class='clear'id='clear' onclick="clear()">
        </div>

part of the JS

function clear() { document.getElementById('display').value = ' '; }

i ultilized this same approach to write the number on the display and it works perfectly, but to delete no, how can I be solving this?

1 answer

2


I believe it’s because clear is a reserved word. See that exchanging clear() for clearx() works.

function clearx() { 
	document.getElementById('display').value = ''; 
}
<div class="visor">
	<input type="text" name="display" id="display">
	<input type="button" value="C" class='clear' id="clear" onclick="clearx()">
</div>

Behold Set.prototype.clear() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/clear


TIP

Maybe that’s not the best option for your case, but you can use a input of the kind reset to clear the form. If you change the div for form and put in a input type="reset" when you click on it it clears all the input within the form

<form class="visor">
	<input type="text" name="display" id="display">
	<input type="reset" value="C">
</form>

  • 1

    Take my +1 for having advised <button type="reset">.. That’s what he was invented for, you really have to use it!

  • @fernandosavio was worth the young force, I think the only drawback of type reset is that you do not control which inputs it erases, if you have 10 input it erases everything... Same problem with CSS with Focus-Within, qq input that focus within the form already activates the class...

  • 1

    The reset is from the form, so it’s supposed to be like this.. D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.