使用JQuery设置下拉框的值

时间:2014-06-13 08:41:46

标签: javascript jquery

我正在尝试使用value设置dropdown框的JQuery。这是我的代码,但它不起作用:

//Check if a box is ticked, if it is set the quantity:
$('.normalbulk').change(function(){
    if(this.checked){
    $('.order_amount').val('26');
    }
});

这是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; ?>

我们的想法是checkedvalue的{​​{1}}设置为26,将order_amount设置为unchecked时为value。我现在的代码什么也没做。#

order_amount代码

 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>

我很欣赏你所有的答案,但它仍然不适合我,我不明白为什么。这是我现在的代码:

$(".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());
   }
});

选中此框后,输出&#34;选中&#34;正如预期的那样,还会打印关闭dropdown的值,但由于某种原因,我无法通过将代码更改为此来设置我所做的值:

       $(this).closest('li').find('.order_amount').val('26');

找出它为什么不起作用。我没有select option,其中value为26.因此它没有设置框来显示任何内容。当我调整代码以显示确实存在的value时,它使用下面提供的解决方案完美地工作。

感谢大家的帮助

5 个答案:

答案 0 :(得分:4)

你的代码是对的,你只需要在这里写下其他部分,就像这样:

$('.normalbulk').change(function(){
    if(this.checked){
      $('.order_amount').val(26);
    }
    else{
      $('.order_amount').val(0);
    }
});

修改

您的下拉列表必须包含值26 vaule的value属性。这样您就可以使用.val()

选择它

Demo with select

Demo

答案 1 :(得分:1)

<强> Working Demo

如果您的复选框是动态添加的,请使用事件委托-jQuery .on()

$(document).on('change','.normalbulk',function(){
    if(this.checked){
        $('.order_amount').val('26');
    }
    else{
        $('.order_amount').val(0);
    }
});

答案 2 :(得分:0)

输入类型复选框的值只能为true或false。例如,您可以将.splitbulk更改为隐藏输入类型。

答案 3 :(得分:0)

分配值使用此查询。

$(".order_amountoption").filter(function () {
                                      return $(this).attr('value') == '26';
                                  }).attr('selected', true);

答案 4 :(得分:0)

$('.normalbulk').click(function(){
    if(this.checked){
         $(".order_amount").val('26');
    }else {
         $(".order_amount").val('0');
    }
});