【问题标题】:Convert Select2 array output to string将 Select2 数组输出转换为字符串
【发布时间】:2019-06-19 08:12:50
【问题描述】:

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

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

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

%5B%5D=x1&source%5B%5D=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>

【问题讨论】:

    标签: javascript html jquery-select2


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的输入,但上面给了我与以前相同的输出:“source[]=x1&source[]=x2”。我想要得到的是:“string=x1,x2”
    • 这仍然不是我想要的。您在 selectedSource 中创建字符串,但未将其添加到表单中。
    • 它通过添加 document.getElementById('string').value = mySelect.val().join(',');谢谢你们的帮助!
    • :-) 很高兴为您提供帮助
    • 嗨,我可以知道name="source[]" 是做什么用的吗?它是强制性的需要在 HTML 中有吗?因为我没有看到它在某处使用。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多