Split values by comma separated string in javascript - javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
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("");
}

The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
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 ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use 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(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from 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>

Related

How to change array variable name dynamically

I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:
I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);

generate list of variables from a FOR loop

var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}

Merging arrays in JavaScript not working

When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null...
function agregar() {
var i = 0,
textarea;
var ar_desc = [];
while (textarea = document.getElementsByTagName('textarea')[i++]) {
if (textarea.id.match(/^desc_([0-9]+)$/)) {
ar_desc.push(textarea.id);
}
}
var desc_count_demo = document.getElementById('desc_count').value;
var desc_count = desc_count_demo - 1;
i = 0;
var ar_desc2 = [];
var campo = null;
while (i <= desc_count) {
campo = document.getElementById(ar_desc[i]).value;
ar_desc2[ar_desc[i]] = campo;
i++;
}
i = 0;
var input;
var ar_url = [];
while (input = document.getElementsByTagName('input')[i++]) {
if (input.id.match(/^url_([0-9]+)$/)) {
ar_url.push(input.id);
}
}
var url_count_demo2 = document.getElementById('url_count').value;
var url_count2 = url_count_demo2 - 1;
i = 0;
var ar_url2 = [];
while (i <= url_count2) {
campo = document.getElementById(ar_url[i]).value;
ar_url2[ar_url[i]] = campo;
i++;
}
// var a = Array.prototype.concat.call(ar_url2, ar_desc2);
while (ar_url2.length) a.push(ar_url2.shift());
function url(data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
}
window.open('alta1.php?'+url(a));
}
EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are
http://localhost/proj1/alta1.php?url_0=inpit&url_1=input
and
http://localhost/proj1/alta1.php?desc_0=input&desc_1=input
But still cannot merge both into one...
One thing I see is your ar_url Array is filled by:
while(input=document.getElementsByTagName('input')[i++]){
if(input.id.match(/^url_([0-9]+)$/)){
ar_url.push(input.id);
}
}
Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc...
Later you do:
ar_url2[ar_url[i]] = campo;
When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array.
Try changing your second loop to:
while(input=document.getElementsByTagName('input')[i++]){
var result;
if(result = input.id.match(/^url_([0-9]+)$/)){
ar_url.push(+result[1]);
}
}
To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.

Calling multiple functions with one button

I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});

fail to create\edit select element with JS

i am trying to create a select element with JS or even edit an existing one yet i seem to be missing something.
this is done in Joomla if this matters.
this is my code:
var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for(int i=0;i<LevelNames.Length;i++)
{
option.innerHTML = LevelNames[i];
option.setAttribute("value",LevelIds[i]);
document.getElementById("cat_chooser").appendChild(option);
document.getElementById("cat_chooser").options.add(option);
}
select.onchange=function()
{
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
document.add(select);
document.appendChild(select);
this is all the ways i tried doing that.
cat_chooser is a SELECT added manualy to the page.
any help?
EDIT:
this is the whole code :
<script language=\"javascript\" type=\"text/javascript\">
//definitions
var LevelNames = new Array();
var LevelIds = new Array();
boolean isFirstRun = true;
//this functions create a Drop Down List
function CreateDDL(pid=null){
//pass arrays for client side, henceforth : var id,var parent_it, var title
<?php echo "\n".$id."\n".$parent_id."\n".$title."\n\n";?>
if(pid){
}
if(isFirstRun)
{
for(int i=0; i < id.length;i++)
{
//if category has no parent
if(parent_id[i] == "1")
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
else{
for(int i=0; i < id.length;i++)
{
//if is a son of our target?
if(parent_id[i] == pid)
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
//finished first run
isFirstRun=false;
//create the actuall drop down
//var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for(var i=0;i<LevelNames.length;i++)
{
var option = new Option(/* Label */ LevelNames[i],
/* Value */ LevelIds[i] );
select.options.add(option);
}
select.onchange=function()
{
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
//document.add(select);
//document.appendChild(select);
document.body.appendChild(select);
}
CreateDDL();
</script>
JavaScript is not Java. You cannot use int or boolean to declare variables. Instead, use var.
JavaScript is not PHP. You cannot define a default value using function createDDL(pid=null)
The .add method is only defined at the HTMLSelectElement.options object.
.appendChild should be used on document.body, not document, because you want to add elemetns to the body, rather than the document.
Working code, provided that <?php .. ?> returns valid JavaScript objects.
<script language="javascript" type="text/javascript"> //No backslashes..
//definitions
var LevelNames = new Array();
var LevelIds = new Array();
var isFirstRun = true;
//this functions create a Drop Down List
function CreateDDL(pid) {
if(typeof pid == "undefined") pid = null; //Default value
//pass arrays for client side, henceforth : var id,var parent_it, var title
<?php echo "\n".$id."\n".$parent_id."\n".$title."\n\n"; ?>
if (pid) {
}
if (isFirstRun) {
for (var i = 0; i < id.length; i++) {
//if category has no parent
if (parent_id[i] == "1")
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
} else {
for (var i = 0; i < id.length; i++) {
//if is a son of our target?
if (parent_id[i] == pid) {
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
//finished first run
isFirstRun = false;
//create the actuall drop down
//var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for (var i = 0; i < LevelNames.length; i++) {
var option = new Option(/* Label */ LevelNames[i],
/* Value */ LevelIds[i]);
select.options.add(option);
}
select.onchange = function () {
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
//document.add(select);
//document.appendChild(select);
document.body.appendChild(select);
}
CreateDDL();
</script>
You need to create a new element and append it in each iteration. Currently, the entire for loop append data to the same option.
Also, in the for loop statement, you typecast the i variable, which you can't do in JavaScript.

Categories