Reputation: 5768
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
Upvotes: 0
Views: 101
Reputation: 2631
$('.normalbulk').click(function(){
if(this.checked){
$(".order_amount").val('26');
}else {
$(".order_amount").val('0');
}
});
Upvotes: 0
Reputation: 17366
Your code is right you just have to write else portion here, like this:
$('.normalbulk').change(function(){
if(this.checked){
$('.order_amount').val(26);
}
else{
$('.order_amount').val(0);
}
});
Edit
Your dropdown must have value attribute with 26
vaule in it. So that you can select it with .val()
Upvotes: 4
Reputation: 20646
Use event delegation- jQuery .on() if your checkboxes are added dynamically.
$(document).on('change','.normalbulk',function(){
if(this.checked){
$('.order_amount').val('26');
}
else{
$('.order_amount').val(0);
}
});
Upvotes: 1
Reputation: 5962
to assign value use this query .
$(".order_amountoption").filter(function () {
return $(this).attr('value') == '26';
}).attr('selected', true);
Upvotes: 0
Reputation: 725
The value of input type checkbox can only be true or false. You can change .splitbulk to input type hidden for example.
Upvotes: 0