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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效