repopulating table with "filtered" data - javascript

See the code below.
I have a table populated with JSON data. The following is intended to clear the table and retrieve only the data with the last name criteria specified by the user.
So far, I'm successful in creating the filter criteria and wiping the table clean. However, I'm having trouble repopulating the table with the filtered results.
Possible hang-ups:
-the Regex: I'm new to RegExp with JS and I'm thinking the syntax is correct, but I'm not entirely sure. I'm also not sure if I'm able to use it the way I am (setting it: filterCriteria = new RegExp("^" + filter.value) and then calling on it to check if last_name object is equal to it: if (contacts.last_name === filterCriteria)
or even if the Regex is working properly, am I able to create a new array based on it the way I'm trying to in that If statement? I.e. is that enough to say, "Take only the objects with a last name that matches the criteria and throw them into a new array"?
Thanks for the help!
var filter = document.getElementById("filter");
filter.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
if ((xhr.readyState === 4) && (xhr.status === 200)) {
var contacts = JSON.parse(xhr.responseText).data,
filterCriteria = new RegExp("^" + filter.value),
i;
for (i = 0; i < contacts.length; i += 1) {
var contactTableBody = document.getElementById("contactTable").lastElementChild,
lastRow = contactTableBody.lastElementChild;
contactTableBody.removeChild(lastRow);
}
if (contacts.last_name === filterCriteria) {
var filterResults = [contacts];
for (i = 0; i < contacts.length; i += 1) {
contactTableBody = document.getElementById("contactTable").lastElementChild;
var newRow = [],
newNameCell = document.createElement("td"),
newPhoneCell = document.createElement("td"),
newEmailCell = document.createElement("td"),
newNameNode = document.createTextNode(contacts[i].last_name + ", " + contacts[i].first_name),
newPhoneNode = document.createTextNode(contacts[i].phone),
newEmailNode = document.createTextNode(contacts[i].email);
newRow[i] = document.createElement("tr");
newRow[i].id = "contact" + i;
newNameCell.appendChild(newNameNode);
newPhoneCell.appendChild(newPhoneNode);
newEmailCell.appendChild(newEmailNode);
newRow[i].appendChild(newNameCell);
newRow[i].appendChild(newPhoneCell);
newRow[i].appendChild(newEmailCell);
contactTableBody.appendChild(newRow[i]);
}
}
}
EDIT:
not 100% on the brace/bracket notation but that should give an idea on how the data is oriented
contacts = JSON.parse(XMLHttpResponse.responseText).data = { [
{ "first_name":"Jim", "last_name":"Cooper", "phone":"8435555555", "email":"jim#halpert.com" },
{ "first_name":"Jim", "last_name":"Aaron", "phone":"1234567890", "email":"jim#beam.com" },
{ "first_name":"Mark", "last_name":"Smith", "phone":"4567891236", "email":"mark#smith.com" },
{ "first_name":"Sally", "last_name":"Smith", "phone":"5469876622", "email":"sally#smith.com" },
{ "first_name":"Mary", "last_name":"Coppersmith", "phone":"6854895212", "email":"mary#coppersmith.com" }
] }

from Santosh initial comment:
I do not know the context, but shouldnt the contacts.last_name be
inside the for loop? Something like this contacts[i].last_name == filterCriteria. If you can the mock up data for contact or a jsfiddle,
it would help.
It was in fact a for loop that was needed. Thanks.

Related

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

Javascript Substring replace with JQuerys contains selector

I'm trying to find a specific row in a column of an HTML table and replace an occurrence of a specific string with a given value.
I tried to use JQuery's .html but it just replaces everything in the row with the given value. A .text().replace() returned me false.
Here's my code:
function ReplaceCellContent(find, replace)
{
//$(".export tr td:nth-child(4):contains('" + find + "')").html(function (index, oldHtml) {
// return oldHtml.replace(find, replace);
//});
$(".export tr td:nth-child(4):contains('" + find + "')").text($(this).text().replace(find, replace));
//$(".export tr td:nth-child(4):contains('" + find + "')").html(replace);
}
$('.export tr td:nth-child(4)').each(function () {
var field = $(this).text();
var splitter = field.split(':');
if (splitter[2] === undefined) {
return true;
} else {
var splitter2 = splitter[2].split(',');
}
if (splitter2[0] === undefined) {
return true;
} else {
$.post(appPath + 'api/list/', {action: 'getPW', pw: splitter2[0]})
.done(function (result) {
ReplaceCellContent(splitter2[0], result);
});
}
});
I'm iterating through every row of the column 4 and extracting the right string. This is going through an AJAX post call to my function which returns the new string which I want to replace it with.
splitter2[0] // old value
result // new value
I hope someone could help me. I'm not that deep into JS/JQuery.
findSmith findJill findJohn
var classes = document.getElementsByClassName("classes");
var replaceCellContent = (find, replace) => {
for (var i = 0; i < classes.length; i++) {
if (classes[i].innerText.includes(find)) {
classes[i].innerText = classes[i].innerText.replace(find, replace);
}
}
}
this replaces all "fill" occurrences to "look".
I love to use vanilla JS, I'm not really a fan of JQuery but this surely should work on your code.
Do like this :
var tds = $("td");
for( var i = 0; i < tds.length ; i++){
if ( $(tds[i]).text().includes("abc") ){
var replacetext = $(tds[i]).text().replace("abc", "test");
$(tds[i]).text(replacetext);
}
}
Say give all your table rows a class name of "trClasses"
var rows = document.getElementsByClassName("trClasses");
for (var I = 0; I < rows.length; I++) {
rows.innerText.replace("yourText");
}
The innerText property would return the text in your HTML tag.
I'm a newbie too, but this should work. Happy Coding!

Javascript, var contains

I currently use this script:
wHandle.setNick = function (arg) {
userNickName = arg;
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
if(fnicks.indexOf(nctr) > -1) {
alert("Unknown Nickname!");
} else {
hideOverlays();
sendNickName();
wjQuery("#mini-map-wrapper").show();
userScore = 0
wjQuery(".btn-needs-nick").prop("disabled", false);
}
};
I wanted to make some kind of filter, so that it blocks these nicknames BUT it isn't covering all of my cases. For example it blocks porno but not pornoo
I want it to use if(contains).
You've essentially done your logic backwards. Instead of checking if the nickname is in your block list, you'd be better served checking if an element of your blocklist is in your nickname like so:
var nick = args.toLowerCase();
for (var i; i < fnicks.length; i++) {
if (nick.indexOf(fnicks[i]) != -1) {
//bad name!
}
}
well I would just loop through the array, and search if the argument you pass (nctr in that case) contains the current entry (fnicks[i]).
you can replace the console.log() by your usual alert()
var arg = "pornoo";
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
for(var i=0,c=fnicks.length;i<c;i++) {
if(nctr.indexOf(fnicks[i]) > -1) {
console.log('boom');
}
}

Filter a child picklist in CRM 2011

I'm trying to convert javascript code from CRM 4.0 to CRM 2011.
I'm having problems with a picklist filter.
My function is on the onchange of the parent picklist. It works the first time but the second it erase everything from my child picklist.
This is the part where I suppose to reset the picklist
if(!oSubPicklist.originalPicklistValues)
{
oSubPicklist.originalPicklistValues = oSubPicklist.getOptions();
}
else
{
oSubPicklist.getOptions = oSubPicklist.originalPicklistValues;
oSubPicklist.setOptions = oSubPicklist.originalPicklistValues;
}
And this is the part where i remove all the option not related:
oTempArray is an array with the options that i want to keep. If a check the "oSubPicklist.getOptions.length" the value is the same that my original picklist.
for (var i=oSubPicklist.getOptions.length; i >= 0;i--)
{
if(oTempArray[i] != true)
{
Xrm.Page.getControl("new_product").removeOption(i);
}
}
Ideas?
Edit: I solved declaring a global var with the originalPickList in the onLoad event and:
oSubPicklist.clearOptions();
for (var i=0; i< oSubPicklist.originalPicklistValues.length; i++)
{
for (var j=0; j< oDesiredOptions.length; j++)
{
if (i == oDesiredOptions[j])
{oSubPicklist.addOption(oSubPicklist.originalPicklistValues[i]);}
}
}
Your code is not very clear to me: May be you could paste all your function code for better understanding but:
This is how you get the options from PickList in CRM 2011
var myOptionSet = Xrm.Page.ui.controls.get("new_product") //get Control
var optionsSet = myOptionSet .getAttribute().getOptions(); //get Options
preferredTimeOptionSet.clearOptions(); //Clear all options
//Create a new Option
var opt1 = new Option();
opt1.text = "one";
opt1.value = 1;
//Add Option
myOptionSet.addOption(opt1);
//Remove Option
myOptionSet.removeOption(1);
Good Example here
Here is another way to do Parent/Child picklists:
function dynamicDropdown(parent, child) {
filterPicklist(parent, child);
}
function parentListFilter(parent, id) {
var filter = "";
if (getParentCode(parent) != "") {
filter = getParentCode(parent);
} else {
// No [ ] match
}
return filter;
}
function filterPicklist(parent, child) {
var parentList = Xrm.Page.getAttribute(parent).getValue();
var childListControlAttrib = Xrm.Page.getAttribute(child);
var childListOptions = childListControlAttrib.getOptions();
var childListControl = Xrm.Page.getControl(child);
var codeToFilterListOn = parentListFilter(parent, parentList);
if (codeToFilterListOn != "") {
childListControl.clearOptions();
for (var optionIndex in childListOptions) {
var option = childListOptions[optionIndex];
// Ignore xx and check for Match
if (option.text.substring(0, 2) != "xx" && option.text.indexOf(codeToFilterListOn) > -1) {
childListControl.addOption(option);
}
}
} else {
// Didn't match, show all?
}
}
function getParentCode(parent) {
//Get Parent Code Dynamically from inside [ ]
var filter = "";
var parentValue = Xrm.Page.getAttribute(parent).getText();
if (parentValue && parentValue.indexOf("]") > -1) {
var parentCode = parentValue.substring(parentValue.indexOf("[") + 1, parentValue.indexOf("]"));
if (parentCode) {
filter = parentCode + " | ";
} else {}
}
return filter;
}
See more here: Parent/Child

Making a variable name a dynamic variable

I hope someone can help me with the following...
I have this code below it is written in classic asp and javascript...
I have this variable in the code below my2String1 how can I make this a dynamic variable like:
my2String1_1
my2String1_2
my2String1_3
I have a database value Recordset2.Fields.Item("article_no").Value which could be the dynamic value like:
my2String1_Recordset2.Fields.Item("article_no").Value (which should do the trick) but I am not sure how to implement it...
while((Repeat1__numRows-- != 0) && (!Recordset2.EOF)) {
var my2String1 = ""+(Recordset2.Fields.Item("article_description").Value)+"";
my2String = my2String1;
var my2regexp = new RegExp(checkduplicates, "ig");
my2Array = my2String1.match(my2regexp);
my2length = my2Array.length;
for (i = 0; i < my2length; i++) {
my2Array[i] = '\''+my2Array[i]+'\'';
}
var arr = (myArray+my2Array).split(',');
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
Repeat1__index++;
Recordset2.MoveNext();
}
If you have any ideas on how to solve this please help me
I'm going to ignore that load of code because it clouding the issue. The feature of JScript you are looking to for is the ability to create named properties on an object:-
var myDescriptions = {}
var name = "Test"
var description = "This is a test"
myDescriptions[name] = description;
Response.Write(myDescriptions[name]);
Would send "This is a test" to the response.

Categories