I'm trying to create a simple calculator using jQuery.
I have a paragraph tag that I'm using as a display. After pressing 'AC' button that clears my display the paragraph tag contains '0'.
What I wanna do is when I press a button with a number I need this '0' to be replaced with the number I pressed because now it goes like '07' or '05'.
I tried:
$('#7').on('click', function() {
if ($('#mainline') == '0')) {
$('#mainline').remove('0');
}
$('#mainline').append('7');
})
But I guess I'm doing something wrong. How should I check if #mainline has '0'?
If #mainline
is a DIV, get its text, then remove leading zeroes with a regexp, then append 7
.
$('#7').click(function() {
$("#mainline").text(function(i, oldtext) {
return oldtext.replace(/^0+/, '') + '7';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainline">0</div>
<button id="7">7</button>
If it's an input, use .val()
instead of .text()
.