2015-03-26 3 views
0

Вот мой вопрос:Split значения по запятой строки в JavaScript

У меня есть RadListBox, и я пытаюсь получить значения и добавить их, так что результат будет отображаться так: «1,2,3 , 4 ', но я возвращаюсь: 1,2,3,4, Кто-нибудь знает, как я могу это достичь?

Проблема начинается здесь:

var sbLocationsIDS = new StringBuilder(); 
      for (i = 0; i < LocationIDS.get_items().get_count(); i++) { 
       sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); 
      } 

Результат: sbLocationsIDS = 1,2,3,4, вместо '1,2,3,4'

Остальная часть Кодекса:

function openNewTab(url) { 
     var captureURL = url; 
     var win = window.open(captureURL, '_blank'); 
     win.focus(); 
    } 

    function GetComparisonsReport(sender, args) { 
     var isValid = Page_ClientValidate('validateComparisons'); 
     if (isValid) { // If its true is going to fire the rest of the code 
      var SessionID = getUrlVars()["SessionID"]; 
      var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value; 
      var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>"); 
      var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>"); 
      var fileType = $find("<%=rcbFileType.ClientID %>"); 
      var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>"); 
      var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>"); 
      var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>"); 
      var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");; 
       if (LocationIDS.get_items().get_count() < 0) { 
       radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert"); 
       return; 
      } 
      if (CategoriesIDS.get_items().get_count() < 0) { 
       radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert"); 
       return; 
      } 
      var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd"); 
      var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd"); 
      var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd"); 
      var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd"); 
      var fileTypeValSelected = fileType.get_selectedItem().get_value(); 


      var sbLocationsIDS = new StringBuilder(); 
      for (i = 0; i < LocationIDS.get_items().get_count(); i++) { 
       sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!! 
      } 
      var sbCategoriesIDS = new StringBuilder(); 
      for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) { 
       sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ","); 
      } 
      var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected)); 
      openNewTab(ComparisonsURL); 
     } 
    } 

    String.format = function() { 
     // The string containing the format items (e.g. "{0}") 
     // will and always has to be the first argument. 
     var theString = arguments[0]; 
     // start with the second argument (i = 1) 
     for (var i = 1; i < arguments.length; i++) { 
      // "gm" = RegEx options for Global search (more than one instance) 
      // and for Multiline search 
      var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm"); 
      theString = theString.replace(regEx, arguments[i]); 
     } 
     return theString; 
    } 

    function getUrlVars() { 
     var vars = {}; 
     var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { 
      vars[key] = value; 
     }); 
     return vars; 
    } 

    // Initializes a new instance of the StringBuilder class 
    // and appends the given value if supplied 
    function StringBuilder(value) { 
     this.strings = new Array(""); 
     this.append(value); 
    } 

    // Appends the given value to the end of this instance. 
    StringBuilder.prototype.append = function (value) { 
     if (value) { 
      this.strings.push(value); 
     } 
    } 

    // Clears the string buffer 
    StringBuilder.prototype.clear = function() { 
     this.strings.length = 1; 
    } 

    // Converts this instance to a String. 
    StringBuilder.prototype.toString = function() { 
     return this.strings.join(""); 
    } 
+0

Разве вы не можете просто удалить последний символ строки с .slice (0, -1)? Или я упрощаю? – sbatson5

+0

Нет, это ошибка –

ответ

1

Проблема заключается в том, что ваша петля добавляет , всегда даже для последнего элемента в цикле.

Вы хотите добавить только все элементы, кроме последних. Есть несколько способов сделать это, простейшее существо: проверить, если текущий элемент является последним, и если да, то не присоединяют ,

var sbLocationsIDS = new StringBuilder(); 
    for (i = 0; i < LocationIDS.get_items().get_count(); i++) { 
     sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value 
     if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list 
      sbLocationsIDS.append(","); //append , 
     } 
    } 

Есть и другие способы сделать это, и в зависимости от того, что вы хотите сделать со значениями в будущем, они могут быть весьма полезными. (Я понимаю, что append в коде на самом деле вызов join, так что это на самом деле более простой вариант)

Добавьте значения списка в массив и использовать Array.join:

var select = document.getElementById("locationId"); 
var options = select.options; 
var optionsArray = []; 
if(options) { 
    for (var i=0; i<=options.length; i++) { 
     //text is the text displayed in the dropdown. 
     //You can also use value which is from the value attribute of >option> 
     optionsArray.push(options[i].text); 
    } 
} 
var sbLocationsIDS = optionsArray.join(","); 

С JQuery , приведенный выше код становится немного более простым:

var optionsArray = []; 
$("#locationId option").each(function(){ 
    optionsArray.push(options[i].text); 
}); 
var sbLocationsIDS = optionsArray.join(","); 

На самом деле, если вы решите использовать йо JQuery, вы можете использовать jquery.map: (идею от Assigning select list values to array)

$(document).ready(function() { 
 
    $("#b").click(function() { 
 
    var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) { 
 
     return (n.value); 
 
    }).join(","); 
 
    alert(sbLocationsIDS); 
 

 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="locationId"> 
 
    <option value="1">1</option> 
 
    <option value="2">2</option> 
 
    <option value="3">3</option> 
 
</select> 
 
<button id="b">Click</button>

+0

Как я могу деформировать ее с помощью одиночных кавычек типа '1,2,3,4' –

+0

'sbLocationsIDS =" '"+ sbLocationsIDS +"' ";' :-). Не сложно, если вы попробуете ... – Nivas

Смежные вопросы