Remove one element from javascript array - javascript

I need to remove one element from javascript array. The element I want to remove is the value of 'NT'. I have a HTML input
<input type="text" id="caseType" size="50"/>
We populate it with
var caseTypeJson = jQuery.parseJSON('${crFilingCaseDetailForm.caseTypes}');
I want to remove one element from the javascript array
jQuery(function () {
jQuery.each(caseTypeJson, function (index, item) {
if(("NT") == item.value){ // remove this element
caseTypeJson.splice(index,1);
}
if (item.value == '${crFilingCaseDetailForm.selectedCase.caseType}') {
jQuery('#caseType').val(item.value + ' - ' + item.description);
jQuery('#selectedCaseType').val(item.value);
}
});
});
This splice approach is not working. In doing some prior research I also tried the javascript delete too and that left the undefined element. Does this seem like a good way to do this?
Thanks,
Tom

You could try using grep.
var values = jQuery.grep(caseTypeJson, function(item) {
if (("NT") != item.value) return item;
});
This will give you an array without the NT value.

Related

Storing Key and Value using Javascript in array

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.
I have tried this by creating a method but it is not working perfectly can you please help me..
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
if (chks.length > 0) {
uninvoiced.push(value);
} else {
uninvoiced.pop(key);
}
console.log(uninvoiced);
}
You need to use splice to remove the element from the array
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
var index = uninvoiced.indexOf(key);
if (chks.length > 0) {
uninvoiced.push(value);
} else if(index > -1){
uninvoiced.splice(index, 1);
}
console.log(uninvoiced);
}
This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this. All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.
That will be hugely more efficient than running a checked selector every time.
The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.
var uninvoiced = [];
function addCheckbox(el) {
var value = el.value.split('|')[1];
if (el.checked) {
uninvoiced.push(value);
} else {
uninvoiced.splice(uninvoiced.indexOf(value), 1);
}
console.log(uninvoiced);
}
foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)">
fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)">
There is a polyfill for indexOf on MDN.

Move array of DOM elements to placeholders in page

I have a design received on my page with a set of placeholders such as:
<span id="ApplicationDate_" class="removeMe"></span>
Plus other many elements as well inside that html. These spans should be replaced by real inputs coming from another area on the page, such inputs look like:
<input type="text" id="ApplicationDate_48596977"/>
So basically what I need to do, is to get all input elements in an array, and then for each element, get its ID up to "_", and search for the span that equals that value, and replace it with this element, then remove all spans with class=removeMe, but I can't achieve it in code, below is what I have reached:
$(document).ready(function () {
var coll = $("input");
coll.each(function () {
var id = this.id; //getting the id here
var substringId = id.substring(0, id.indexOf('_') + 1); //getting the span id
this.appendTo("#" + substringId); //having problems here..
});
$(".removeMe").each(function () {
this.remove();
});
});
it tells me this.appendTo is not a function, any help or hint is much appreciated.
TL;DR - Just use:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});
Here's why:
this is a DOM element, but .appendTo() is a jQuery method. You probably just need to wrap this in a call to jQuery:
$(this).appendTo("#" + substringId);
That would place the <input> element inside the <span> like this:
<span id="ApplicationDate_" class="removeMe">
<input type="text" id="ApplicationDate_48596977"/>
</span>
But, then you call:
$(".removeMe").each(function () {
this.remove();
});
First, you would have the same problem as above - this is a DOM element, but .remove() is a jQuery method. Second, it would be better to just call $(".removeMe").remove() - wrapping it in a .each() is redundant. Third, that would remove the span, and the input along with it. That's not what you are trying to do is it?
If you want to replace the span with the input, use .replaceWith():
var coll = $("input");
coll.each(function () {
var substringId = this.id.substring(0, id.indexOf('_') + 1);
$("#" + substringId).replaceWith(this);
});
It seems like the whole thing could be rewritten, taking advantage of the attribute starts with selector, as:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});

For Loop to Programmatically hide elements

I am currently trying to programmatically hide div elements on a page using an Array and loop in jQuery, but it doesn't seem to work.
I have done alerts and console.log to confirm the array is firing and the loop is working through the items, but it's the .hide() method that seems to be giving issue. Any help would be appreciated.
Thanks
$(document).ready(function(){
var divsToHide = ["fin_0", "fin_1", "fin_2", "fin_3", "fin_4", "fin_5",
"fin_6", "fin_7", "fin_8", "fin_9", "fin_10", "fin_10-1", "fin_10-2", "fin_10-3",
"fin_10-4", "fin_10-5", "fin_10-6", "fin_10-7", "fin_10-8", "fin_10-9", "fin_20",
"fin_21", "fin_22", "fin_23"];
$.each(divsToHide, function(index, value)
{
var currentDiv = "div#" + value;
var stringCurrent = currentDiv.toString();
var currentHide = $(' stringCurrent ');
console.log(currentDiv);
currentHide.hide();
});
});
You should probably use:
var currentHide = $(stringCurrent);
Your code
var currentHide = $(' stringCurrent ');
has no reference to stringCurrent variable, it just try to find <stringCurrent> element.
Even better, you should use
$.each(divsToHide, function(index, value)
{
$("#" + value).hide()
});
since an element id should be unique to the document
You need to remove the ' around stringCurrent. Otherwise your string is not interpreted but jquery searches for ' stringCurrent '

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}

Categories

Resources