Reputation: 117
I have a simple a+b php calculator, but you select the inputs from a dropdown.
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
if (isset($_POST['radio'])) {
$radio_input = $_POST['radio'];
$radio_input1 = $_POST['radio1'];
echo "$";
echo $radio_input1 + $radio_input;
}
}?>
<form action="asdindex.php" method="post">
<ul>
<li>
<select name="radio">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</li>
<li>
<select name="radio1">
<option value="1.2">1.2</option>
<option value="3.1">3.1</option>
<option value="0.3">0.3</option>
<option value="1.2">1.2</option>
</select>
</li>
</ul>
<input type= "submit" name="submit"value="submit"/>
</form>
The question is how can i print the result without using a submit button/input/. I know that you can't do it with PHP. But not sure how to do it with JQ or smt. else.
Upvotes: 2
Views: 6721
Reputation: 14810
You can use Javascript to do this. See the below JS
function addValues() {
var a = 0,
b = 0;
var e = document.getElementById("radio");
a = e.options[e.selectedIndex].value;
var e1 = document.getElementById("radio1");
b = e1.options[e1.selectedIndex].value;
alert(parseFloat(a) + parseFloat(b));
}
Add the above JS inside a <script>
before you close the <body>
.
The function will be invoked by clicking a button. The HTML for button would be as follows
<button onclick="addValues()">Click to add</button>
Update
See the fiddle
Updated HTML
<ul>
<li>
<select name="radio" id="radio">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</li>
<li>
<select name="radio1" id="radio1">
<option value="1.2">1.2</option>
<option value="3.1">3.1</option>
<option value="0.3">0.3</option>
<option value="1.2">1.2</option>
</select>
</li>
</ul>
<button onclick="addValues()">Click to add</button>
<br/> Result=
<span id="result"></span>
Updated JS
function addValues() {
var a = 0,
b = 0;
var e = document.getElementById("radio");
a = e.options[e.selectedIndex].value;
var e1 = document.getElementById("radio1");
b = e1.options[e1.selectedIndex].value;
document.getElementById("result").innerHTML = (parseFloat(a) + parseFloat(b));
}
Update
If you don't want the button, you can just listen for the change
event of the select
.
See this fiddle
Upvotes: 0
Reputation: 3968
You can use jQuery, function can be executed on change
of second dropdown
,
sum gets calculated without hitting any button.
$(function(){
$('.check2').change(function(){
var data1= parseInt($('.check1').val());
var data2= parseInt($('.check2').val());
alert(data1 + data2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="check1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="check2">
<option value="3">3</option>
<option value="4">4</option>
</select>
Upvotes: 2