multiple comma seperate value compare using JS - javascript

I want validation using a comma separated value.
Here in the image, there are two fields : one is "Saloon Price" (value : 10,10,10,10), and another is "Saloon Offer Price" (value : 11,11,11,11).
The first value must be lower than the second.
Saloon price Value >= Saloon Offer Price value
validations based on first value of saloon price and saloon offer price same for second , 3rd ...n
var size_weight_lengh = size_weight.split(',');
var saloon_price = validator.getFieldElements('saloon_price').val(),
saloon_price_lengh = saloon_price.split(',');
var saloon_offer = validator.getFieldElements('saloon_offer_price').val(),
saloon_offer_lengh = saloon_offer.split(',');
if(saloon_price_lengh.length === saloon_offer_lengh.length) {
for(var i=0; i<= saloon_price_lengh.length-1; i++) {
if((saloon_price_lengh[i]) >= (saloon_offer_lengh[i])) {
return true;
}
return false;
}
}

Split the string and then do a value comparison of two array elements.
It uses "break" and "continue" to reduce the unnecessary iterations over the loop.
Here is the full script. Adjust the functionality accordingly.
$(document).ready(function () {
var value = ComparePrice();
alert(value);
});
function ComparePrice() {
var salonOfferPrice = $('#saloon_offer_price').val();
var salonPrice = $('#saloon_price').val();
var offerPriceArray = salonOfferPrice.split(",");
var priceArray = salonPrice.split(",");
var isValid = false;
if (offerPriceArray.length == priceArray.length) {
for (var i = 0; i < offerPriceArray.length; i++) {
for (var j = 0; j < priceArray.length; j++) {
if (i == j) {
if (offerPriceArray[i] < priceArray[j]) {
alert(offerPriceArray[i] + "is less than" + priceArray[j]);
isValid = true;
}
else {
alert(offerPriceArray[i] + "is greater than or equal" + priceArray[j]);
return false;
}
}
else {
continue;
}
}
}
}
return isValid;
}

You have to do value by value comparison.
var sp="10,20,30"; //get your field values here
var sop="5,10,15";
var spArr = sp.split(','); //split the values using comma
var sopArr = sop.split(',');
if(spArr.length === sopArr.length){
for(var i in spArr){
if(parseInt(spArr[i])<parseInt(sopArr[i])){
//throw some error or your logic goes here.
}
}
}
Just make sure that you accept only numbers and comma using some regex check in the text field.

Related

if condition in javascript function not working

I need to compare the values and return the message.But the message returned always. How can i do it?
Javascript:
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
for (var i = 0; i < grid.rows.length - 1; i++) {
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]")
var cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (txtcurrentrcvamount > cell) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}
You need to take the value of your input:
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val()
// ^^^^^^
Since you're comparing numbers, and val() and text() return strings, you should convert your values to numbers before doing the comparison:
if (Number(txtcurrentrcvamount) > Number(cell))
Do note that Number(someStringThatIsNotANumber) will return NaN
Because your scope of a variable (txtcurrentrcvamount) is limited in between for loop, That's why this not working outside the loop scope.
for more detail, you can view this post...scope of variables
For using this variable in if condition you have initialized it before the for loop...
EDIT:
Try this may this help you either. I think there some other finding to suppose you have two rows in your grid then which row value you want to check because this always return last row value... and if there a number value for both of the variable assignment txtcurrentrcvamount ,cell then it should be work perfectly.
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
var txtcurrentrcvamount ;
var cell;
for (var i = 0; i < grid.rows.length - 1; i++) {
txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val();
cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (Number(txtcurrentrcvamount) > Number(cell)) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}

Shift letters from input to the next in alpabhet

I have been searching the web and I have found a few examples about my current problem, and all seems to be addressing the same topic: deciphering text. But I cannot find anything written in javascript. I gave it a shot, but I'm stuck when trying to convert the string in to an array.
Lets say that the current alphabet is
var alpabhet=[
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö'
];
And I have a string ammj, that I enter in the input. Then I want to be able to shift with right and left key and view the output of that current shift. So a shift of two (2) would result in the string cool. And a shift of 5 for the string åjjg would also result in cool.
So my main concern is, how can I convert a user input to an array with javascript?
I have a input filed:<input id="text_to_be_shifted" type="text"> and then I'm trying to loop the input and arrange into a array
var values = {};
var inputs = document.getElementById('text_to_be_shifted');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}
Have a look at my fiddle: http://jsfiddle.net/p8kqmdL1/
Here you have a live and working example, with a check so that shifting letter 'a' with -1 will convert it to last letter of the alphabet 'ö', -2 to 'ä' e.t.c. and shifting last letter of alphabet with 1 will set it to 'a', with 2 to 'b' e.t.c:
var alpabhet=[
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö'
];
var values = {};
var inputs = document.getElementById('text_to_be_shifted');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}
function outputText(number){
var newtext = [];
var inputtext = document.getElementById('text_to_be_shifted').value.split('');
inputtext.forEach(letter=> {
var ind_ofLetter = alpabhet.indexOf(letter);
ind_ofLetter = ind_ofLetter + number;
if (ind_ofLetter < 0){
ind_ofLetter = alpabhet.length + ind_ofLetter;
}else if(ind_ofLetter > alpabhet.length-1){
ind_ofLetter = ind_ofLetter - alpabhet.length;
}
newtext.push(alpabhet[ind_ofLetter]);
});
document.getElementsByClassName('output')[0].innerHTML = newtext.join('');
}
function shiftUp() {
var currentShift = document.getElementById('currentShift');
var number = currentShift.innerHTML;
number++;
currentShift.innerHTML = number;
outputText(number);
}
function shiftDown() {
var currentShift = document.getElementById('currentShift');
var number = currentShift.innerHTML;
number--;
currentShift.innerHTML = number;
outputText(number);
}
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
console.log('left arrow')
shiftDown()
}
else if (e.keyCode == '39') {
console.log('right arrow')
shiftUp()
}
}
<b>Current shift: </b><span id="currentShift">0</span>
<br><input id="text_to_be_shifted" type="text">
<div id='output' class="output"></div>
There is only one input, so there is no point in looping over it.
To get an array, you should use something like:
document.getElementById('text_to_be_shifted').split("");
You can then use the map function to shift the elements
let arr = document.getElementById('text_to_be_shifted').split("");
let shifted = arr.map((c) => alpabhet[(alpabhet.indexOf(c) + 1) % alpabhet.length]).join("");
in your for loop you can utilize the charAt() function to get the individual character at a given index. W3 schools has a good lesson on this function if needed: https://www.w3schools.com/jsref/jsref_charat.asp
var inputArray = [];
var inputs = document.getElemenById('text_to_be_shifted');
for(let i = 0; i < inputs.length; i++){
inputArray[i] = inputs.charAt(i);
}
Something like this should work to get you an array with a single letter at each index.

Array text to numbers, find matching values and sort

I have an array which looks like this:
["1,8", "4,6,8", "8,9", "6,9"]
1/ I would like to turn it in to this
[1,8,4,6,8,8,9,6,9]
2/ I would then like to find matching values, by looking for the most number:
[8]
This first has been solved with this:
var carArray = ["1,8", "4,6,8,7,7,7,7", "8,9", "6,9"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
setResult('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
}
else{
//3)/4) ???
setResult('sorting?');
}
//below is only for test display purposes
function setResult(res){
console.log(res);
}
3/ If the are no matching values like this
[1,8,4,6,5,7]
4/ Then I need to compare this array to another array, such as this
[6,7,4,1,2,8,9,5]
If the first number in <4> array above appears in <3> array, then get that number, ie in the above example I need to get 6. The <4> array will be static values and not change. The numbers is <3> will be dynamic.
EDIT Not the most elegant of answers, but I do have something working now. I didn't compare the original array directly with the second array, instead used simple if/else statements to do what I needed:
var carArray = ["1,5", "4", "8,2", "3,9,1,1,1"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
console.log('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
console.log(maxOccurring);
}
else {
// If not occuring, match from a list
if(jQuery.inArray("6", arr) !== -1) { console.log('6'); }
else if(jQuery.inArray("9", arr) !== -1) { console.log('9'); }
else if(jQuery.inArray("7", arr) !== -1) { console.log('7'); }
else if(jQuery.inArray("5", arr) !== -1) { console.log('5'); }
else if(jQuery.inArray("4", arr) !== -1) { console.log('4'); }
else if(jQuery.inArray("1", arr) !== -1) { console.log('1'); }
else { console.log('not found'); }
}
Example Fiddle
Step 1 is fairly easy by using javascript's join and split methods respectively:
var arr = carArray .join().split(',');
For step 2, several methods can be used, the most common one using an object and using the elements themselves as properties. Since you only need to get the most occurring value if there is a reoccurring value, it can be used in the same loop:
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
After the above, the variable maxOccurring will contain the reoccurring value (if any) and max will contain the times it occured
For step 4 the easiest way is to loop through the compare array and get the element that occurs in the input array:
var cmpArr = ['6','7','4','1','2','8','9','5'];
//find the first occurrence inside the cmpArr
res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();
The above uses an in place function which is called immediately to be able to use return. You could also just use a loop and assign res when found, then break from the loop.
Last update, an alternate fiddle where the above is converted to a single function: http://jsfiddle.net/v9hhsdny/5/
Well first of all the following code results in four matching answers since the jQuery selectors are the same.
var questionAnswer1 = $(this).find('input[name=questionText]').val();
var questionAnswer2 = $(this).find('input[name=questionText]').val();
var questionAnswer3 = $(this).find('input[name=questionText]').val();
var questionAnswer4 = $(this).find('input[name=questionText]').val();
var carArray = [questionAnswer1, questionAnswer2, questionAnswer3, questionAnswer4];
You could use the eq(index) method of jQuery to select the appropriate element. However having 4 inputs with the same name is a bad practice.
Well lets say that the carArray has 4 different values which all consist out of comma separated numbers. You could then do the following:
var newArr = [];
carArray.forEach(function(e) {
e.split(",").forEach(function(n) {
newArr.push(n);
});
});
Well then we got to find the most occurring number. JavaScript doesn't have any functions for that so we will have to find an algorithm for that. I found the following algorithm on this stackoverflow page
var count = function(ary, classifier) {
return ary.reduce(function(counter, item) {
var p = (classifier || String)(item);
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
return counter;
}, {})
}
var occurances = count(newArr);
It isn't clear to me what you're trying to do in step 3 and 4, so can't answer those at the moment.
var ary = ["1,8", "4,6,8", "8,9", "6,9"];
var splitted = ary.reduce(function(acc, item) {
return acc.concat(item.split(','));
}, []);
var occurences = splitted.reduce(function(acc, item) {
if (!acc.hasOwnProperty(item)) acc[item] = 0;
acc[item] += 1;
return acc;
},{}),
biggest = Object.keys(occurences).reduce(function (acc, key) {
if (occurences[key] > acc.occurences) {
acc.name = key;
acc.occurences = occurences[key];
}
return acc;
},{'name':'none','occurences':0}).name;
var vals=["1,8", "4,6,8", "8,9", "6,9"];
// 1) turn into number array
var arrNew=[];
for(var i=0; i<vals.length; i++)
{
arrLine=vals[i].split(",");
for (var j=0;j<arrLine.length;j++) { arrNew.push (parseInt(arrLine[j])) }
}
//result:
alert(arrNew.join(";");
// 2) find most common
var found=[];
for(var i=0; i<arrNew.length; i++) {
// make an array of the number of occurrances of each value
if (found["num"+newArray[i]]) {
found["num"+newArray[i]] ++ ;
} else {
found["num"+newArray[i]]=1;
}
}
var mostCommon={count:0,val:"ROGUE"};
for (x in found) {
if (found[x] > mostCommon.count) {
mostCommon.count=found[x].count;
mostCommon.val=x;
}
}
// result :
alert(mostCommon.val);
//3) not quite sure what you meant there
// 4) unique values:
// at this point the 'found' list contains unique vals
var arrUnique=[];
for (x in found) {
arrUnique.push[x];
}
// result :
alert(arrUnique.join(";"))
//sort:
arrUnique.sort(function(a, b){return a-b});
(This won't work in most browsers) but on a side note, when ES6 becomes widely supported, your solution could look like this:
var arr1 = ["1,8", "4,6,8", "8,9", "6,9"];
var arr2 = arr1.join().split(',');
var s = Array.from(new Set(arr2)); //Array populated by unique values, ["1", "8", "4", "6", "9"]
Thought you might like to see a glimpse of the future!
1.
var orgArray = ['1,8', '4,6,8', '8,9', '6,9'];
var newArray = [];
for (var i in orgArray) {
var tmpArray = orgArray[i].split(',');
for (var j in tmpArray) {
newArray.push(Number(tmpArray[j]));
}
}
2.
var counts = {};
var most = null;
for (var i in newArray) {
var num = newArray[i];
if (typeof counts[num] === 'undefined') {
counts[num] = 1;
} else {
++(counts[num]);
}
if (most == null || counts[num] > counts[most]) {
most = num;
} else if (most != null && counts[num] === counts[most]) {
most = null;
}
}
I don't understand the question 3 and 4 (what "unique order" means) so I can't answer those questions.

iterate two arrays and perform AND / OR comparison = return true

Here is my current filter function (quite incomplete)
$('input:checkbox.types').click(function(){
filterMarkers();
});
function filterMarkers() {
var checked = [];
$('input:checkbox.types:checked').each(function(){
checked.push($(this).val());
});
checked.sort();
var andor = '';
var andor = $('[name="and-or"]:checked').val();
if(andor == 1) {
// and
console.log(checked);
for (var i = 0; i < markers.length; i++) {
var types = markers[i]['types'].split(",");
types.sort();
console.log(types);
}
} else {
// or
}
}
Here is an image of what I have so far.
http://snag.gy/rKSTA.jpg
Let us say this for simplicity.
A = checked checkboxes
B = array with values of current item in map marker iteration / current iteration marker
I was able to get the values of the checked checkboxes. I was also able to convert the comma delimited string of each marker into an array. I would like to be able to check if B contains ANY of A (OR) and be able to check that B must contain A (AND).
Any ideas?
Here is the page in question for those wanting a 'feel' for what I am trying to accomplish. Thanks!
https://www.cablework.co/company
This page outputs what I have currently to console.
Once I can figure this out, I will then be able to hide/show markers based on the result.
Here's an example function. You would run test on every marker against the types array.
http://jsfiddle.net/q1k6e74d/5/
function test(op,types,marker){
var pass;
if(types.length === 0 || marker.length === 0){
return false;
}
if(op==="and"){
pass = true;
for(var i in types){
if( $.inArray(types[i],marker) == -1 ){
pass = false;
}
}
}else{ //or
pass = false;
for(var i in marker){
if( $.inArray(marker[i],types) !== -1 ){
pass = true;
}
}
}
return pass;
}
var a = [1,4];
var b = [1,5];
console.log("test a",a,"and b",b,test("and",a,b));
console.log("test a",a,"or b",b,test("or",a,b));
Could be shorter but it's easiest to understand this way I think.

Javascript: How do I replace text between two delimiters?

var record = "HENRY|5|58|L581"
How do I change the above to:
record now equals "HENRY|Five|58|L581"
I know how to retrieve the index of the first '|' and the second '|' .. I know how to retrieve the number '5' into a string.
But I have no idea how to actually replace that 5 with the word Five.
The part |5| could be any number from 1-50
Something like that ?
record = record.replace('|5|', '|FIVE|');
Following edit :
To replace any number by FIVE, you can do
record = record.replace(/\|\d+\|/, '|FIVE|');
If you want to replace with something depending of the number (maybe you want TEN when the number is 10), then you'll have to do some work :
record = record.replace(/\|\d+\|/, function(str) {
var number = parseInt(str,10);
return 'FIVE'; // here build a new string and return it
});
You can do this, for example:
var record = "HENRY|5|58|L581"
var recordArray = record.split("|");
for (var i = 0; i < recordArray.length; i++) {
if (recordArray[i] === "5") {
recordArray[i] = "FIVE";
}
}
record = recordArray.join("|"); // or record = recordArray.toString();
Is this what you want to achieve?
UPDATE
If you want any number, you can set it into a function:
function changeNumber(textVar, valueToChange, replaceText) {
var recordArray = textVar.split("|");
for (var i = 0; i < recordArray.length; i++) {
if (recordArray[i] === valueToChange) {
recordArray[i] = replaceText;
}
}
return recordArray.join("|"); // or recordArray.toString();
}
See demo.
I presume you don't want to replace any number with "five", you want to replace with the actual string representing number.
var repl = [0, 1, ....];
var to = ["zero", "one", ...];
var recordArray = record.split("|");
for (var i = 0; i < recordArray.length; i++) {
recordArray[i] = to[indexOf(recordArray[i], repl)];
}
finStr = recordArray.join("|");

Categories