Reputation: 303
I would like to be able to select the closest h2 heading to the fieldset that contains the pizza selection options and set the text for the heading using jQuery. I have so far been unable to do it.
HTML:
<div id="pizzaForm">
<fieldset>
<form class="pure-form">
<legend>Pizza</legend>
<label><b>Pizza Type: </b></label>
<select id="pizza">
<option name="margarita">Margarita</option>
<option name="deep-pan">Deep Pan</option>
<option name="stuffed-crust">Stuffed Crust</option>
</select>
<span style="float:right">
<label><b>Pizza Size: </b></label>
<select id="pizzaSize">
<option name="e-small" data-price="4.99">Extra Small - £4.99</option>
<option name="small" data-price="5.99">Small - £5.99</option>
<option name="medium" data-price="6.99">Medium - £6.99</option>
<option name="large" data-price="8.99">Large - £8.99</option>
<option name="e-large" data-price="9.99">Extra Large - £9.99</option>
<option name="f-size" data-price="10.99">Family Size - £10.99</option>
</select>
</span>
</form>
</fieldset>
<fieldset style = "border-top:0px">
<form class="pure-form">
<legend><b>Toppings (99p Each): </b></legend>
<input type="checkbox" name="onions">Onions</input>
<input type="checkbox" name="mushrooms">Mushrooms</input>
<input type="checkbox" name="peppers" >Peppers</input>
<input type="checkbox" name="olives" >Olives</input>
<input type="checkbox" name="garlic" >Garlic</input>
<input type="checkbox" name="peperoni" >Peperoni</input>
<input type="checkbox" name="cheese" >Pesto</input>
</form>
</fieldset>
<h2 id="cost" style= "float:left; margin-top:-3cm; margin-left: 9cm; border: solid black 2px; padding: 5px"> TEST </h2>
<br>
</div>
JS:
$(document).on("change","#pizzaSize", function() {
$("input[type='checkbox']").prop('disabled', false);
var selectionPrice = $('option:selected', this).attr('data-price');
var selectionInt = parseFloat(selectionPrice, 10);
pizzaCost = selectionInt;
$(this).closest('h2').text(pizzaCost);
calculateCost(pizzaCost, toppingCost, sideCost, drinkCost, desertCost, desertSizeCost, drinkSizeCost, sideSizeCost);
});
Upvotes: 0
Views: 68
Reputation: 11317
closest()
does only work to get the fieldset for your control. If you know that the h2 comes after the fieldset on the same level, you could do:
$(this).closest('fieldset').nextAll('h2').first();
But it depends on what you mean with 'closest'. You might want to have a look at the jQuery tree traversal functions.
Upvotes: 1