This Calculator model will take inputs from the Number 1 and Number 2 fields and when the user clicks on the relevant operator the result will be displayed in the Results field.
For log10(), to radian, to degree, sin, cos, tan operations only require one input. Hence, the user is instructed to input the values to the 1st field only.
First, before proceeding with the calculation, we need to obtain the values from the text boxes.
For that we should include all the form elements inside a form.
The result is directed to the same page. Therefore we will use the form action as $_SERVER['PHP_SELF'] and the method as post.
Next, we can obtain the values in the text boxes.
$_POST['form_element_name'] will give you the value of the respective element.
We can write the php code as follows (in the <head>) to obtain the value from Number 1 and Number 2 fields.
<?php
$num1=$_POST['num1']; //num1 is the name of the 1st input field.
$num2=$_POST['num2']; //num2 is the name of the 1st input field.
?>
If we use the above code, initially before the form is submitted the page will show an error saying $num1 and $num2 are undefined. So to get rid of this, we can first check for the submission.
For that we use the 'isset' function to check if the element is set. In this case the button where user selects the operator.
if (isset($_POST['submit1']))
The above statement will check if the submit button with the name submit1 is set.
In our case, if the button that does the addition operation is named add,
if (isset($_POST['add']))
So far, we have obtained the 2 numbers. After that we can assign each button to perform the relevant calculations as below.
Likewise, for each operator we can code how the calculation should be done.
Now, to display the answer in the Results field, the answer should be added as the value attribute in the input tag.
<input type="text" name="result" value="<?php echo $result ?>" >
But here also we must wait for the submission. It can be any of the buttons. So we will use the below code to check if at least one of the buttons is set.
For the rest of the buttons also this code can be changed as below.
A small issue is that after the submission, Number 1 and Number 2 fields will be empty. In order to retain the value, the following code can be added to the value attribute of the each input field.
First, it will be checked if any of the buttons are set. If so, the value we assigned to $num1 will be echoed here. Else, the field will be empty. The same can be done to the Number 2 field.
Here's a demo of how it works.
Comments
Post a Comment