Reputation: 2348
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!
Upvotes: 6
Views: 39841
Reputation: 82913
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>
Upvotes: 14
Reputation: 9382
$(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've changed your HTML a bit (more understandable field names/IDs), but you should get the basic idea.
I also removed your hidden field as I see no point in duplicating data. Your selected value from the select box will already be sent to the server and then you have an hidden field that does exactly the same.
You can get the quantity server-side with the keyword itemQuantity_3 (in PHP $_POST['itemQuantity_3']).
Upvotes: 1
Reputation: 53
You could use the .html() function after you selected the span you want to modify e.g.:
$('span').html('$'+(x*1.5))
Upvotes: 3
Reputation: 663
You can use the text() function to set or get the text of an HTML Element (does not work on input fields!). Your code example 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>
Upvotes: 1
Reputation: 3855
I would suggest adding an id to the span then doing something like this:
$('#spanID').text($(this).val());
Upvotes: 3