codevixen codevixen - 6 months ago 15
Javascript Question

change an alert to display on screen jquery

I'm building a calculator and need to know how to display a number when clicked on and so far I just am able to create an alert. Here's the code.

var add = function (x,y){
return x+y;
};
var subtract = function (x,y){
return x-y;
};
var multiply = function (x,y){
return x*y;
};
var divide = function (x,y){
return x/y;
};

$(document).ready(function() {
$(".num").click(function(){
alert("button");
});
});


And here's a glimpse of the html:

<div id="wrapper">
<table id="grid">
<tr>
<td><button class="num">7</button></td>
<td><button class="num">8</button></td>
<td><button class="num">9</button></td>
<td><button class="sym">+</button></td>
</tr>
</table>
</div>


Thank you!

Answer

you can use something like this

$(document).ready(function() {
    $(".num , .sym").click(function(){
        $('#screen').append($(this).text());
    });
    $('.total').on('click',function(){
        var calc = eval($('#screen').text());
        $('#screen').text(calc);
    });
    $('.clear').on('click',function(){
        $('#screen').text('');
    });
});
#screen{
  padding : 10px;
  background : red;
  color: #fff;
  font-size: 20px;
}
.num , .sym , .clear{
  height : 30px;
  width : 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">

<div id="screen">

</div>
<table id="grid">
    <tr>
        <td><button class="clear">C</button></td>
    </tr>
    <tr>
        <td><button class="num">7</button></td>
        <td><button class="num">8</button></td>
        <td><button class="num">9</button></td>
        <td><button class="sym">+</button></td>
    </tr>
    <tr>
        <td><button class="num">4</button></td>
        <td><button class="num">5</button></td>
        <td><button class="num">6</button></td>
        <td><button class="sym">-</button></td>
    </tr>
    <tr>
        <td><button class="num">1</button></td>
        <td><button class="num">2</button></td>
        <td><button class="num">3</button></td>
        <td><button class="sym">*</button></td>
    </tr>
    <tr>
        <td><button class="total">=</button></td>
    </tr>
</table>
</div>

Comments