Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - change <span>text</span> with dropdown selector

This might 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 I'm having a hard time figuring out how to also use JQuery to simultaneously update a text in the area when different values are chosen with a dropdown selector. The Script and HTML looks 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 dropdown selector, I also want the value in the <span>$1.50</span> to update. Example - selecting a value of '1' makes the text string in span show $1.50 - selecting a value of '2' in the dropdown makes the text string show $3.00 (or whatever) etc!

Any clues are greatly appreciated! Thanks!

like image 215
Jamison Avatar asked Apr 11 '11 12:04

Jamison


People also ask

How do I change the text inside a span?

Use the textContent property to change the text of a span element, e.g. span. textContent = 'Replacement text' . The textContent property will set the text of the span to the provided string, replacing any of the existing content.

How do I select a span containing a specific text value using jQuery?

To check if a span element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the span . If it is, the includes() method returns true , otherwise false is returned.

How do you value a span?

jQuery: Set a value in a span Set a value in a span using jQuery. JavaScript Code: $(document). ready(function(){ $('#button1').


2 Answers

Try this:

<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> 
like image 93
Chandu Avatar answered Sep 19 '22 15:09

Chandu


I would suggest adding an id to the span then doing something like this:

 $('#spanID').text($(this).val());
like image 36
Munzilla Avatar answered Sep 22 '22 15:09

Munzilla