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!

+6
source share
6 answers

Try the following:

 <script type='text/javascript'> $(function() { $('#mycups3').change(function() { var x = $(this).val(); $('#myhidden3').val(x); $(this).next("span").text("$" + (x * 1.5).toFixed(2)); }); }); </script> 
+13
source

I would suggest adding id to the span, and then do something like this:

  $('#spanID').text($(this).val()); 
+3
source

You can use the .html () function after selecting the range that you want to change, for example:

 $('span').html('$'+(x*1.5)) 
+3
source

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> 
+1
source

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']).

+1
source

use the html method.

 $('span').html("$1.50"); 
0
source

Source: https://habr.com/ru/post/885650/


All Articles