Lets get this out of the way. "I know almost nothing about JavaScript"! Any of the JavaScript code I am using is taken form sites that show examples of JavaScript. As well, I have searched the Stackoverflow forum for people having similar issues. If I missed a topic that will fix my problem, please let me know.
I have a dropdown list that has a list of stock shares:
<select name="shares" id="shares">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
</select>
I am currently using this JS code and it will displaying the cost to the screen for the only the first number in the dropdown list:
<script>
var stock_position = <?php echo $stock_position; ?>;
var shares = document.buy_shares.shares;
var cost = stock_position * shares.value;
document.write(cost);
</script>
However, I have no idea how to make the cost change when a new share amount is selected from the dropdown list. As well, I think I read somewhere that said "document.write()" might not be the best option to display the cost to the screen? Any input would be appreciated.
Thanks for your help!
I made this code for you. In this first I print your values in a p
tag then when the user changes share it will again change the p
tag html. Here is a fiddle link for a live demo
$("#demo").html($("#shares").val());
$("#shares").on('change',function(){
var values = $(this).val();
$("#demo").html(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="shares" id="shares">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
</select>
<p id="demo"></p>
</div>
the variable I created name values you can use that variable for calculation like values*stock_position or any kind of calculation.
If you have stock position values from php then you have to use ajax for get that value in javascript.
I guess what you would like to do is something like this:
DEMO: http://jsfiddle.net/vdbr24m7/
HTML:
<select name="shares" id="shares">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
</select>
Cost : <span id="cost"></span>
JavaScript:
var stock_position = 10;// set by PHP
function showCost(shares){
var cost = stock_position * shares;
$("#cost").text(cost);
}
$(function() {
var $list = $("#shares");
$list.change(function(){
showCost($(this).val());
});
showCost($list.val());
});
Hope this helps.