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条)

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境