groseler groseler - 3 months ago 10
HTML Question

Jquery send result of SUM to div

I want to:
Get value from select, sum with other values, and place it inside a span.

Can I send the result of a value to a div/span without having to submit with a button? Is that possible?

please look at my fiddle: https://jsfiddle.net/groseler/3mq1ye1y/

HTML



$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);

});
$("#result").html(resultSum);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
Result should appear here ---> <span id="result" ></span></div>




Answer

Your code works after a bit change. You have only some typo. You need to add the $("#result").html(resultSum) into the change callback.

You don't need to submit anything. Submit is for the forms and after submitting the data almost always go to the server side code

$(function () {  
  $("#field16-1").change(function() {
    var val = $(this).val();
    var comEx = "150";
    var youngDriver = "100"; 
    var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
     $("#result").html(resultSum);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
  <option value="">Please select...</option>
  <option value="120">120</option>
  <option value="230">230</option>
  <option value="260">260</option>
 </select>
 <div>
<span id="result" ></span></div>

Comments