JQuery - change <span> text </span> with a drop down menu
It may be easy, but I'm a jQuery dunce and keep getting errors!
Basically, I have a basic JQuery 1.4+ function that updates an input value, but now itβs hard for me to understand how to use JQuery to update text in an area at a time when different values ββare selected using the dropdown selector. Script and HTML look like this:
$(function() { $('#mycups3').change(function() { var x = $(this).val(); $('#myhidden3').val(x); }); });
<form action="" method="post"> <input type="hidden" id="myhidden3" name="quantity" value="1" /> <input type="submit" name="submit" class="button" id="" value="Button" /> <select id='mycups3'> <option value='1'>1 Item</option> <option value='2'>2 Items</option> <option value='3'>3 Items</option> </select> <span>$1.50</span> </form>
What I want to add: When using the drop-down selector, I also want the value in <span>$1.50</span>
updated. Example. Selecting the value "1", the text line in the span
shows $ 1.50 - choosing the value "2" in the drop-down list, the text line shows $ 3.00 (or something else), etc.
Any tips are greatly appreciated! Thanks!
You can use the text () function to set or retrieve the text of an HTML element (does not work in the input fields!). An example of your code might look like this:
<script type='text/javascript'> $(function() { $('#mycups3').change(function() { var x = $(this).val(); $('#myhidden3').val(x); $('form span').text('$'+(x*1.5)); }); }); </script>
Working example: http://jsfiddle.net/peeter/fyFxp/
$(document).ready(function() { $('#itemQuantitySelect_3').change(function() { var itemPrice = 1.50; var itemQuantity = $(this).val(); var quantityPrice = (itemPrice * itemQuantity).toFixed(2); $(this).next("span").html("$" + quantityPrice); }); });
I changed my HTML a bit (more comprehensible field names / identifiers), but you should get the basic idea.
I also deleted your hidden field as I see no reason to duplicate the data. The value you selected from the selection field will already be sent to the server, and then you have a hidden field that will be exactly the same.
You can get the number of the server side with the keyword itemQuantity_3 (in PHP $ _POST ['itemQuantity_3']).