I'm trying to display the results from my tip calculator into a table using php, when I enter in the bill amount and tip I want it to have a table of two columns and three rows for the first column I want it to display these results-
bill amount:,tip percent: and total amount: with the results from the tip calculator to show in the other column.
I just need help starting this code off using php so that my results show in a table from what I input, here is my code that I have so far:
<!DOCTYPE html>
<form id="calculator">
<p>Amount: <input id="amount" /></p>
<p>Tip Percentage: <input id="percentage" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<p><input type="submit" /></p>
</form>
</html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function calculate () {
var amount = $('#amount').val();
var percentage = $('#percentage').val();
var tip = amount * (percentage / 100);
var total = Number(amount) + tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
return false;
}
$('#calculator').submit( calculate );
</script>
As correctly pointed out in comments, you can do everything with jQuery (without PHP).
$('#calculator').submit(function()
{
var amount = $('#amount').val();
var percentage = $('#percentage').val();
// do some basic validation
if(!$.isNumeric(amount) || amount<0 ||
!$.isNumeric(percentage) || percentage<0)
{
$('#prompt').html('Please enter correct values!');
return false;
}
var tip = amount * (percentage / 100);
var total = Number(amount) + tip;
$('#tip').html(tip.toFixed(2));
$('#total').html(total.toFixed(2));
return false;
});
I've just added some basic validation to your input, corrected some layout (i.e. #tip
and #total
are results, so you can create a result table outside the form), added a prompt for displaying errors and changed val()
to html()
to update results. Hope it helps.