Peyo Peev Peyo Peev - 4 years ago 71
HTML Question

Get value without submitting it

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.

Lal Lal
Answer Source

See this fiddle

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download