I am trying to put a condition in jQuery's map function. My issue is that I don't want the same number in the map function value. When it is the same I want to display an alert box. My map function code is like this:
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
return this.value;
}).get();
If I get a value like 1,2,3,4,5 it's ok, but if I get a value like 1,2,3,2,5, I want to display an alert box. Is it possible?
How to put a condition in jQuery's map function?
function change_rank() {
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if() {
} else { }
return this.value;
}).get();
var vals = []
$('input[type=text][class = cate_rank]').each(function(){
if($(this).val() && (typeof vals[$(this).val()] == 'undefined')){
vals[$(this).val()] = 1;
var last_val = $(this).val();
}else if($(this).val() && (typeof last_val != 'undefined') && parseInt(last_val) > parseInt($(this).val())){
alert('Whooah! Something went terribly wrong! Inputs don\'t have values ordered incrementally!');
}else{
alert('Whooah! Something went wrong! We got two inputes with same value!');
}
});
Check this,
var rankbox= $(".test").map(function() {
return this.value;
}).get();
var sorted_arr = rankbox.slice().sort();
var results = [];
for (var i = 0; i < rankbox.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
var rankbox= $(".test").map(function() {
if($.inArray(this.value, results) > -1){
alert(this.value+" is duplicate");
}
return this.value;
}).get();
I took reference of this link
If you are Looking to check dup you can try this:
var x=[1,2,3,2,5]
var has=!x.every(function(v,i) {
return x.indexOf(v) == i;
});
console.log(has);//true means dup found else not found.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can try with a object. check this:
function change_rank() {
var temp = {};
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if(temp[this.value]==undefined) {
temp[this.value] = this.value;
} else {
alert('the same value');
}
return this.value;
}).get();
Related
The first time the function fires I get this result:
output1:test
The output2 2 alert is not firing. I know something is probably undefined in alert Does anyone know why the value won't be added in the multidimensional array?
I expect this to display after the false1:
output2:test2
Also if you want to fiddle with the code here it is:
https://jsfiddle.net/ndf0sjgf/1/
var carSelectedArray = [
[null]
];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
} else {
arrayempty = false;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}
Your loop works well, however your didn't define your array well.
there is only 1 dimension here :
var carSelectedArray = [[null]];
So replace with this :
var carSelectedArray = [[],[]];
PS : null is not required
and at the beginning in your function, you define arrayempty to false, so you can remove this :
else {
arrayempty = false;
}
Solution here : https://plnkr.co/edit/Qikalr0jc54R3MRSea4G?p=preview
var carSelectedArray = [[],[]];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}
i have a jsp page and call a JS function which is in some abc.js file from this JSP page.
i have included this js file to jsp page.
JSP JavaScript Code:-
function doFinish(tableId, col, field)
{
var oldselectedCells = "";
var selItemHandle = "";
var selRightItemHandle = "";
var left = -1;
var right = -1;
// Get the table (tBody) section
var tBody = document.getElementById(tableId);
// get field in which selected columns are stored
var selectedCellsFld = document.getElementById(tableId + datatableSelectedCells);
selectedCellsFld.value = oldselectedCells;
for (var r = 0; r < tBody.rows.length; r++)
{
var row = tBody.rows[r];
if (row.cells[col].childNodes[0].checked == true)
{
selectedCellsFld.value = oldselectedCells +
row.cells[col].childNodes[0].id;
selItemHandle = row.cells[col].childNodes[0].value
oldselectedCells = selectedCellsFld.value + datatableOnLoadDivider;
left = selItemHandle.indexOf("=");
right = selItemHandle.length;
selRightItemHandle = selItemHandle.substring(left+1,right);
var index=getColumnIndex(tBody,"Name");
if(index!=null)
{
if(field == 1)
{
window.opener.document.TemplateForm.eds_asbactionscfg_item_handle_child_physpart.value = selRightItemHandle;
window.opener.document.TemplateForm.ChildPhysicalPart.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 2)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 3)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
}
}
}
window.close();
}
JS Code:-
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggest some solution.
getColumnIndex(tBody,columnName) function works fine.
as if it matches this if condition
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
so that it returns something.
but when you replace this
var index=getColumnIndex(tBody,"Name"); so that coulmnName would be "Name" in String.
And it doesn't match with any columnName so that your condition going to be wrong and function doesn't return anything.
var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggestion is put some else condition on that and return some error message like this :
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
} else{
// put some error message
// return null
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine
From this, I'm assuming that there isn't anything wrong with the implementation of your getColumnIndex function, so your issue with getting an undefined value must have to do with when this function is returning a value.
but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
This leads me to assume that your tBody variable is not being set correctly, given that the "function works fine".
I'm assuming there is a case in your code where the conditions of your getColumnIndex function is not met.
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
// If your code reaches this point, then the prior conditions have not been met
// You can choose to do something else here for return false/undefined etc.
return undefined;
}
i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;
I have an array of JSON objects like so:
var myArray = [
{name:'foo',number:2},
{name:'bar',number:9},
{etc.}
]
How do I detect if myArray contains an object with name="foo"?
Unless I'm missing something, you should use each at the very least for readability instead of map. And for performance, you should break the each once you've found what you're looking for, no reason to keep looping:
var hasFoo = false;
$.each(myArray, function(i,obj) {
if (obj.name === 'foo') { hasFoo = true; return false;}
});
With this:
$.each(myArray, function(i, obj){
if(obj.name =='foo')
alert("Index "+i + " has foo");
});
Cheers
for(var i = 0; i < myArray.length; i++) {
if (myArray[i].name == 'foo')
alert('success!')
}
var hasFoo = false;
$.map(myArray, function(v) {
if (v.name === 'foo') { hasFoo = true; }
});
I have a little Problem. I have seven <select>'s. The go from left to right counting up.
<select id="sel_1" onchange="evalonsubmit('sel_1',1);">
<select id="sel_2" onchange="evalonsubmit('sel_2',2);">
That goes from 1 to 7 in this way.
The logic is easy. On click check if the value is -1 if it is disable everything on the right and set it to -1. if it is not -1 then enable the the right of the clicked one (+1 so to say)
And that's the code:
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if(ElementID.value = -1) {
for (var i = n + 1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById();
newValue.disable = true;
newValue.value = -1
}
} else {
var newID = "sel_"+(n+1)
var newValue = document.getElementById();
newValue.disable = false;
}
}
Can somebody kind JS hacker help me?
I just fixed some simple mistakes in your code ..
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if (ElementID.value == -1){
for (var i=n+1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
newValue.disable = true;
newValue.value = -1
}
} else {
var newID = "sel_"+(n+1)
var newValue = document.getElementById(newID);
newValue.disable = false;
}
}
Not quite sure what you want, but it probably should be:
if (ElementID.value == -1){
// ^--- two = , otherwise you assign the value
and
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
// pass parameter ---^
Same in the else branch.
Besides that, I would give your variables more meaningful names. E.g. ElementID lets you assume that the value is an ID. But it is not. It is a DOM element. Same for newValue.
You're missing the parameter in a couple of your calls to document.getElementById, and the property for disabling a <select> is disabled, not disable. You also have = where you need ==.
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if (ElementID.value == -1){
for (var i=n+1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
newValue.disabled = true;
newValue.value = -1;
}
} else {
var newID = "sel_"+(n+1);
var newValue = document.getElementById(newID);
newValue.disabled = false;
}
}
Why not do this:
HTML:
<div class="wrapper">
<select onchange="evalonsubmit(this);" />
<select onchange="evalonsubmit(this);" />
<select onchange="evalonsubmit(this);" />
</div>
JS:
function nextElement(current)
{
do
current = current.nextSibling;
while (current && current.nodeType != 1);
return current;
}
function evalonsubmit(elem)
{
if(elem.value == -1)
while(elem = nextElement(elem)) {
elem.disabled = true;
elem.value = -1
}
else if(elem = nextElement(elem))
elem.disabled = false;
}
That removes the need for ids on the <select> elements, as following elements can be grabbed with .nextSibling. The nextElement() function is to avoid grabbing text nodes.