want to get textbox value - javascript

I have two textboxes which values are like:
312,315
315,313
I want to get a string with all the values, for example: 312,315,313 skipping existing values in both fields.
My code:
var firstbox = $("#firstbox").val();
var secondbox = $("#secondbox").val();
var newvalue = $(firstbox).not(secondbox).get();
console.log(newvalue);
But it's not working, how can I get my desired output using JQuery?
thanks.

You could concatenate the two, joining them with a comma.
You would then have a comma delimited string, so you could split at the comma, remove any duplicate values, then rejoin the remaining values.
Something like this:
var firstbox = $("#firstbox").val(),
secondbox = $("#secondbox").val(),
boxes = firstbox + "," + secondbox,
arr = boxes.split(","),
res = [];
$.each(arr, function(i, el){
if($.inArray(el, res) === -1){
res.push(el);
}
});
$("#res").html(res.join(",").replace(/(^,)|(,$)/g, ""));
Fiddle

Maybe this will give you a hint in the right direction:
// get comma seperated list of all values
var allValues = $('#firstbox').val() + ',' + $('#secondbox').val();
// make an array out of them
var allValuesArray = allValues.split(',');
// sort out repeated values
// by creating a new array 'distinctValues'
var distinctValues = [],
currentValue,
valuesLookup = {};
for (var i = allValuesArray.length - 1; i >= 0; i--) {
currentValue = allValuesArray[i];
if (!valuesLookup[currentValue]) {
valuesLookup[currentValue] = true;
distinctValues.push(currentValue);
}
}
// output the result to the console
console.log(distinctValues.join(','));

Related

Why is the comparison operator not finding matches in Google App Script?

I have a small function that takes a string (strOrder = 658492-1), splits it into just the first part before the '-' and compares it to values in a cell in a spreadsheet (which is also split). If it is a match, it should add the spreadsheet row to an array. Unfortunately, it is not finding any matches, but even the log shows they are the same. Help!
function getLinks2(strOrder) {
var mLinks = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Main');
var data = mLinks.getDataRange().getValues();
var boxOrder = '';
var shortOrder = '';
var sOrder = '';
var arrLinks = [];
data.shift();
strOrder = strOrder.replace(/\s/g, "");
var oTemp = strOrder.split('-');
boxOrder = oTemp[0];
Logger.log('boxOrder:x' + boxOrder + 'x');
for (var i = 0; i < data.length; i++) {
shortOrder = data[i][4].toString();
shortOrder = shortOrder.replace(/\s/g, "");
var soTemp = shortOrder.split('-');
sOrder = soTemp[0];
Logger.log('sOrder:x' + sOrder + 'x');
if (boxOrder == sOrder) {
Logger.log('match');
arrLinks.push(data[i]);
//the item matches the order id
} else {
//item does not match the order id
} // end if order id matches
} // end for loop through data
return arrLinks;
} // end function getLinks2
Here are the Log results:
boxOrder:x685492x
sOrder:x658492x
sOrder:x658492x
sOrder:x658492x
sOrder:x699249x
sOrder:x698406x
(I used the 'x' around the strings to check if there were extra spaces.)
What am I missing?
Thanks for any help!

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

Split url into tab in javascript

input:
"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
javascript:
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');
output of my js code:
0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1
i want to split my url into a map with key:value like this
output:
origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false
My code not do exactly what i want in output, what is wrong ?
You should split with
var params = parmeters.split('&')
and then split all the values you get
for (var i = 0,len = params.length; i<len;i++){
var data = params[i].split("=", 2); // Max 2 elements
var key = data[0];
var value = data[1];
...
}
i think your wrong ' characters
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);
use this like..
good luck
A possible solution using ECMA5 methods and assuming that your string is always the same pattern.
var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
slice = src.split(/[\/|?|&]/).slice(3),
data = slice.reduce(function (output, item) {
var split = item.split('=');
output[split.shift()] = split.shift();
return output;
}, {
origin: slice.shift(),
destination: slice.shift(),
goDate: slice.shift()
});
document.body.appendChild(document.createTextNode(JSON.stringify(data)));

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

Categories

Resources