将Select2数组输出转换为字符串 [英] Convert Select2 array output to string

查看:85
本文介绍了将Select2数组输出转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将select2数组转换为要在形式中使用的字符串.目前,我的输出如下所示:

I am trying to convert select2 array to string to be used in form. Currently my output looks like this:

?source%5B%5D = x1& source%5B%5D = x2

?source%5B%5D=x1&source%5B%5D=x2

我希望将其转换为逗号分隔的字符串.我尝试使用'string = source.join()',但是我的字符串输出为空.

i am looking to convert it to have comma separated string. I have tried to use 'string = source.join()' but output of my string is empty.

%5B%5D = x1& source%5B%5D = x2& string =

%5B%5D=x1&source%5B%5D=x2&string=

我想要得到的是这样的:

What I am trying to get is something like this:

string%5B%5D = x1,x2

string%5B%5D=x1,x2

<form action="/action_page.php">    
   <select class="form-control select2" multiple="" id="source" name="source[]" style="width: 250px;">

      <optgroup label="Group1">
         <option>x1</option>
         <option>x2</option></optgroup>
         <optgroup label="Group2">
            <option>y1</option>
            <option>y2</option></optgroup>
         </select>
         <script type="text/javascript">
            $(".select2").select2({
            tags: true
            });
         </script>
         <script type="text/javascript">
         string = source.join()
         </script>
         <input type='hidden' name='string' ></input>
         <br><br>
         <input type="submit">
      </form>

推荐答案

我不知道这是否真的是您想要的,但这可以为您提供线索.

I don't know if it's really what you want, but that can give you clues.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>

<form onsubmit="onFormSubmit()">

   <select class="form-control select2" multiple="" id="source" style="width: 250px;">
      <optgroup label="Group1">
         <option>x1</option>
         <option>x2</option>
       </optgroup>
       <optgroup label="Group2">
          <option>y1</option>
          <option>y2</option>
      </optgroup>
   </select>
   <script type="text/javascript">
      // Init Select2
      var mySelect = $(".select2").select2({
        tags: true
      });
      // On form submit
      var onFormSubmit = function(){
        // Get selected value (only if at least one selected)
        if (mySelect.val() !== null && mySelect.val().length > 0) {
            var selectedSource = "string=" + mySelect.val().join(',');
            alert(selectedSource);
        }
      }
   </script>
   <input type='hidden' name='string' />
   <br><br>
   <input type="submit" />

</form>

这篇关于将Select2数组输出转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆