Reputation: 41614
I have a few select options boxes on one page, I'm trying to get the value and text of the selected options and insert them into hidden fields, if I select the first one only(first time after page reload)it doesn't work, but if I select the first one and the second one after page reload it works,
to make it work I have to first select an option from the second select box and all will work.
here's a link to the site. http://www.snappy-pizza.net/sides.php
any help would be appreciated.
<form>
<input type="hidden" value="MIXED SALAD" />
<select class="select" name="select3" id="select3">
<option value="0">0</option>
<option value="1.99">1</option>
<option value="1.99">2</option>
<option value="1.99">3</option>
<option value="1.99">4</option>
<option value="1.99">5</option>
<option value="1.99">6</option>
<option value="1.99">7</option>
<option value="1.99">8</option>
</select>
</form>
<form>
<input type="hidden" value="Onion Rings" />
<select class="select" name="select" id="select">
<option value="0">0</option>
<option value="1.99">1</option>
<option value="1.99">2</option>
<option value="1.99">3</option>
<option value="1.99">4</option>
<option value="1.99">5</option>
<option value="1.99">6</option>
<option value="1.99">7</option>
<option value="1.99">8</option>
</select>
</form>
<script>
$(function () {
$('#my-add-button-sides').click(function () {
var qty = [];
var price = [];
var items_names = [];
var final_price = 0;
$('.select option:selected').each(function () {
var $this = $(this);
if (($this.text()) > 0) {
qty.push($this.text());
price.push($this.val());
items_names.push($this.parent().prev('input:hidden').val());
}
$this.attr('selected', '');
});
var total_price = $.map(qty, function (n, i) {
return n * price[i];
});
$.each(total_price, function () {
final_price += this;
});
var qty_items = $.map(qty, function (n, i) {
return n + "--" + items_names[i];
});
var randomNumber = Math.floor((Math.random() * 9000) + 200);
$('input[name=my-item-id]').val(randomNumber);
$('input[name=my-item-name]').val(qty_items.join('\n'));
$('input[name=my-item-price]').val(final_price);
});
});
</script>
Upvotes: 1
Views: 223
Reputation: 27866
I've tested your code and I have a final_price result even if only the first select box is used. I select the first box value 1 and get 1.99 response. Check your example.
Update PizzaPrice is not defined is the error I get. Try to put the first block of code also in the $(function() {} which is a wrapper for the ready() function. Your code doesnt have acces to PizzaPrice variable.
Upvotes: 2