I am trying to set the value of a dropdown box using JQuery. This is my code but it is not working:
//Check if a box is ticked, if it is set the quantity:
$('.normalbulk').change(function(){
if(this.checked){
$('.order_amount').val('26');
}
});
This is the HTML
<!-- If stock code contains "BULK" Display check box -->
<? $bulk = get_field('description', $product->ID);
if(strpos($bulk, 'Bulk') !== false): ?>
Normal Bulk:<input type="checkbox" name="normalbulk" value="bulk" class="normalbulk"> (26 Pallets)
Split Bulk: <input type="checkbox" name="splitbulk" value="bulk" class="splitbulk"> (16 Pallets)
<? endif; ?>
The idea is that when it is checked set the value of order_amount to 26 and when it is unchecked set the value to 0. The code I have at the moment does nothing.#
order_amount code
Amount <select id="order_amount<?= $product->ID; ?>" name="amt" class="order_amount">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I appreciate all your answers guys, but it is still not working for me and I Can't understand why. This is my code now:
$(".normalbulk").change(function(){
if(this.checked){
console.log("checked");
console.log($(this).closest('li').find('.order_amount').val());
}else{
console.log("unchecked");
console.log($(this).closest('li').find('.order_amount').val());
}
});
When the box is checked it outputs "checked" as expected, also prints the value of the closes dropdown but for some reason I just can't set the value which I do by changing the code to this:
$(this).closest('li').find('.order_amount').val('26');
Found out why it wasn't working. I did not have a select option with a value of 26. Therefor it did not set the box to display anything. When I adjusted the code to display a value that did exist it worked perfectly using the solutions provided below.
Thank you for the help everyone