douying1119 2014-12-03 08:53
浏览 398
已采纳

jQuery push数组插入逗号

I have few select boxes with same class. But when I use jQuery array push method to get all selected values in that class as an array it simply adds a comma (,) before each values. It works fins with static values. Issue is when I add values to select box from a PHP array. Here is how my select boxes code looks like

<select name="add_purch_item1" class="add_purch_item">
    <option value="">----select----</option>
    <?php if(!empty($pro_list1)) { foreach($pro_list1 as $products) { ?>
        <option value="<?php echo $products->sku; ?>"><?php echo $products->product_name; ?></option>
    <?php } } ?>
</select>

<select name="add_purch_item2" class="add_purch_item">
    <option value="">----select----</option>
    <?php if(!empty($pro_list2)) { foreach($pro_list2 as $products) { ?>
        <option value="<?php echo $products->sku; ?>"><?php echo $products->product_name; ?></option>
    <?php } } ?>
</select>

And I have added a click function to a button. When clicks it will get all selected values as an array. here is my jQuery code,

var selected = [];

    $('.add_purch_item').each(function () {
        selected.push($(this).val());
    });

    alert(selected);

And when I try select box with static values it gives correct output. See here an example

I am getting this wrong output in dynamic values. That unwanted comma is my issue. How to avoid that? I have tried string replace too. Wrong Output

  • 写回答

2条回答 默认 最新

  • dragonfly9527 2014-12-03 08:57
    关注

    It is happening because blank values are also inserted. You need to check that selected value is not blank before inserting.

    $('.add_purch_item').each(function () {
        var val = $(this).val();
        if (val) {
            selected.push(val);
        }
    });
    

    See updated fiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试