簡體   English   中英

使用PHP和JavaScript以逗號分隔獲取多個值

[英]Get Multiple Values with comma separated Using PHP and JavaScript

您好,我是PHP和JavaScript的新手。 我有一個代碼下拉復選框。 我想嘗試以逗號分隔的1,2,3來獲取選中選項的值

我的問題是,當我運行代碼時,輸​​出的末尾有一個逗號,例如1,2,3,而我想要的輸出是1,2,3

這是我的代碼

HTML部分

<select id="agency" multiple="multiple">
<?php
if (is_array($rating_agencies) && !empty($rating_agencies)) {
    foreach ($rating_agencies as $rating_agencie) {
        echo '<option value="'.$rating_agencie->ID.'"';
        echo '>';
        echo $rating_agencie->name;
        echo '</option>';
    } 
}           
?>
</select>
<input type="button" id="btnSelected" value="Get Selected" />

Java腳本

<script type="text/javascript">
    $(function () {
        $('#agency').multiselect({
            includeSelectAllOption: true
        });
        $('#btnSelected').click(function () {
            var selected = $("#agency option:selected");
            var message = "";
            selected.each(function () {
                message += $(this).val() + ",";
            });
            alert(message);
        });
    });
</script>

jQuery.mapArray#join

.get()將返回basic-array而不是array-of-objects

$(function() {
  $('#agency').multiselect({
    includeSelectAllOption: true
  });
  $('#btnSelected').click(function() {
    var message = $("#agency option:selected").map(function() {
      return this.value;
    }).get();
    alert(message.join(','));
  });
});

使用slice刪除最后一個逗號。

$('#btnSelected').click(function () {
    var selected = $("#agency option:selected");
    var message = "";
    selected.each(function () {
        message += $(this).val() + ",";
    });
    message = message.slice(0, -1);
    alert(message);
});

這是您的問題解決方案,或者您可以使用@Rayon。

使用切片功能:

<script type="text/javascript">
    $(function () {
        $('#agency').multiselect({
            includeSelectAllOption: true
        });
        $('#btnSelected').click(function () {
            var selected = $("#agency option:selected");
            var message = "";
            selected.each(function () {
                message += $(this).val() + ",";

            });
            message = message.slice(0, -1);
            alert(message);
        });
    });
</script>

嘗試獲取值而不是選項:selected,它可能對您有用

var selected = $("#agency").val();

php中使用rtrim方法

// $commaString = "1,2,3,";
  $string = rtrim($commaString,",");
  // output 
  // 1,2,3

Java語言編寫

var comma_string = "1,2,3,";
string = comma_string.replace(/,+$/,'');

您可以在任何一方使用它作為邏輯。

只需在“ if”語句之前使用$rating_agencies = array_filter($rating_agencies)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM