jQuery grep return on Multidimensional Array - javascript

I am learning jQuery and am having issues trying to figure out how to select elements in a multidimensional array. I have a select list with database IDs and I want to set a var with the cost field in the database according to the id that selected. I have all the pieces except for translating the selected ID to a cost. Can someone please help me with getting this right please?
var rangeListData = [{"idrange_list":"1","range_cost":"0","target_range_name":"Self Only"},{"idrange_list":"2","range_cost":"1","target_range_name":"1 Space"},{"idrange_list":"3","range_cost":"2","target_range_name":"2 Spaces"},{"idrange_list":"4","range_cost":"3","target_range_name":"3 Spaces"},{"idrange_list":"5","range_cost":"4","target_range_name":"4 Spaces"},{"idrange_list":"6","range_cost":"5","target_range_name":"5 Spaces"}];
$('#slctPowerTarget').change(function () {
var targetID = $('#slctPowerTarget').val();
var cost $.grep(rangeListData, function(e) { return e.idrange_list == targetID }); // this is the line that is wrong
$('#spanTotalEffectsCost').text(cost);
});
If I put targetID in where cost is it lists fine. But when I try to look this up nothing happens. It is not right somehow and I am not sure what else to try. I think I get how idrange_list == targetID is supposed to match them but not sure how to call the related range_cost.
Thanks for any help you can offer! I read through the docs at jquery.com but can't seem to wrap my head around them.

You can do this :-
// Get the Multidimensional Array first
var data = $.grep(rangeListData, function (e) {
return e.idrange_list === targetID
});
// Get the range cost from the array
var cost = data[0].range_cost;
// Check the value in console for debugging purpose
console.log(cost);

Here is the final code. I also added an IF clause in there in case they select the default setting. This way it will reset instead of tossing an error and keeping page calculations working no matter if they change the drop downs or go back to "Select..."
$('#slctPowerRange').change(function () {
var rangeID = $('#slctPowerRange').val();
if (rangeID > 0) {
var rdata = $.grep(rangeListData, function (e) {
return e.idrange_list === rangeID
});
var rcost = rdata[0].range_cost;
}
else {
var rcost = 0 ;
}
$('#hdnRangeCost').val(rcost);
});

Related

PDF.js Setting a field value?

I hope you're all doing well. So I've been working with PDF.js by Mozilla for a while now. We're using it to display PDF forms to be filled out on a mobile app. Everything works great, I'm just trying to implement a feature where you can cache the users entries so that they can resume from where they left off. For a few reasons I can't just download the PDF to save it and then load it back up when they wat to resume.
Essentially I want to store all the user entries and the Field ID for each of them, which I've already gotten working, and then when the user wants to resume I want it to load the empty PDF, and then automatically re-populate all the fields with the cached entries.
I know I could set the individual text fields, but when I do that it doesn't apply to the annotationStorage so when I parse the form, those fields are read as blank.
I've tried the following lines of code in an attempt to set a field value with the id "5R"
PDFViewerApplication.pdfDocument.annotationStorage.setValue('5R', "Shirboogle");
PDFViewerApplication.pdfDocument.annotationStorage.getAll()['5R'].value = "Shirboogle";
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
objs['Address 1 Text Box'][0].value = "Shirboogle";
// and
objs['Address 1 Text Box'][0].defaultValue = "Shirboogle";
// This will actually set the value of the text field, but when I look for it in annotationStorage OR
// getFieldObjects() the value is still unchanged.
document.getElementById('pdfjs_internal_id_5R').value = 'Shapoopsies';
along with many other attempts. I've looked all over and nothing seems to be available, so if you have any ideas please let me know!
In case anyone is having trouble with this, here is the solution I came up with. It seems to work great for my use case but may not be sufficient for every case. I figured I'd at least share what I got to work.
It basically sets everything manually. There are still some UI elements I need to make an if statement for to set, but anyways. Here's my code. Good luck :)
function getFieldValue(id) {
return PDFViewerApplication.pdfDocument.annotationStorage.getAll()[id].value;
}
async function getFieldObjById(id) {
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
for(var i=0; i<Object.values(objs).length; i++) {
if(Object.values(objs)[i][0].id == id) {
return Object.values(objs)[i][0];
}
}
}
async function setFieldValue(id, val) {
var fElementId = "pdfjs_internal_id_" + id;
var fObject = await getFieldObjById(id);
var objType = fObject.type;
// Depending on the element type we set the value accordingly.
if(objType == 'text') {
document.getElementById(fElementId).value = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'checkbox') {
document.getElementById(fElementId).checked = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'combobox') {
document.getElementById(fElementId).selectedIndex = val;
var sLabel = document.getElementById(fElementId).options[document.getElementById(fElementId).selectedIndex].label;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: sLabel});
}
}

using javascript with a string that contains

Hi I am currently using java to hide certain tabs and fields on my forms depending on the population of dropdowns, for example here is a code that is working:
//Display Transfer tab if it is a transfer application
var ctrlApplicationType = Runner.getControl(pageid, 'ApplicationType');
ctrlApplicationType.on('change', function(e)
{
if (this.getValue() == 2)
{
var tabs = pageObj.getTabs(); tabs.show(2);
}
else
{
var tabs = pageObj.getTabs(); tabs.hide(2);
}
}
);
In the example above the dropdown is fed from a lookup table and returns the primary key INT, hence ==2 works fine.
However I now have a problem when I am trying to get this to work with a checkbox, because the problem is a checkbox can have multiple options.
My lookup table for checkbox has 5 options, so if i ticked option 1, 2 and 3, the field (string) is stored as 1,2,3.
What I need to do is to do change the above code so it returns true if it contains 1, ie
if (1,2,3) contains 1 then true
if (2,3) contains 1 then false.
Any ideas would be much appreciated
Okay, against my better judgement (I'd really like to see you make your own attempt based on the information I've already given you), here you go...
var selectedString = "1,2,3"; // from your code, this is this.getValue()
var selectedArray = selectedString.split(","); // split the string into an array using a comma (,) as the split point
var foundInArray = selectedArray.includes('1'); // foundInArray is now a boolean indicating whether or not the value '1' is one of the values in the array.
if(foundInArray)
{
// do the found action
}
else
{
// do the not found action
}
If you want to compare against integer values instead of string values, that's easy enough too.
var integerArray = selectedArray.map(function(x){ return parseInt(x); });
var foundInArray = integerArray.includes(1);
Finally, all of this can be chained into a one-liner:
if(selectedString.split(",").map(function(x){return parseInt(x);}).includes(1))
{
// do found action
}
else
{
// do not found action
}
To iterate through a fixed list and show/hide each, you can do this...
var possibleTabs = [1,2,3,4,5];
for(n in possibleTabs)
{
if(selectedString.split(",").map(function(x){return parseInt(x);}).includes(n))
{
var tabs = pageObj.getTabs(); tabs.show(n);
}
else
{
var tabs = pageObj.getTabs(); tabs.hide(n);
}
}
This, of course, assumes that there is a relation between the checkbox value and the tabs. If there's not, then you're going to have to list them all out as individual if/elseif/else statements, and that is going to get out of hand really quickly.

How to remove elements from a selector

I'm struggling to get a piece of code to work but I'm not a jquery guy so please bear with me.
I have an outer DIV ($scope). It contains all kinds of inputs.
I find all the entries for each input type and filter them to get the ones with values. These are stored in $entries.
$inputs contains all the inputs regardless of type or status.
What I'm trying to do is remove $entries from $inputs to leave the difference.
It doesn't work, and at the moment I'm not getting any errors firing back, so nothing to go on.
My first thought is that jquery is unable to match the elements in one list with the other as it just holds an index, not the actual object. This could be totally wrong (please refer back to line 1).
Either way, I need to find a way of getting all elements and segegating them into 2 bits - those with values and those without.
All help appreciated.
function inputLoaded(isPostback) {
if (typeof Page_Validators !== "undefined") {
$scope = $(".active-step:first");
$inputs = $scope.find(inputs);
$cb = $scope.find(checkboxes).filter(":checked");
$rb = $scope.find(radios).filter(":checked");
$sb = $scope.find(selects).filter(function () { return $(this).val() !== "None"; });
$ta = $scope.find(textareas).filter(function () { return $(this).val(); });
$tb = $scope.find(textboxes).filter(function () { return $(this).val(); });
$entries = $cb.add($rb).add($sb).add($ta).add($tb);
// Do things with $entries here
// Get elements that have not got entries
$el = $inputs.remove($entries);
}
}
The not() method can take a jQuery object whose contents will be excluded from the jQuery object you apply it to. It looks exactly like what you're looking for:
// Get elements, excluding entries.
$el = $input.not($entries);

Search items in a list, what is good to use?

It is not really a issue, im just wondering I have a list with alot of names and a search function bounded to it. It is all done in jquery and just put every element on display none when it is not matched with the input
It works perfect but I am not really sure this is the 'cleanest' way to do this, cause every element gets updated with a bunch of css styles everytime.
Is it worth to try out angular or some similar solution to achieve it or a complete overkill for such a small task?
Updated:!
My current code:
var value = $input.val(),
$persons = $teamCatagory.find('li');
$persons.hide();
var found = $persons
.filter(function () {
$persons.hide();
return $(this).text()
.match(new RegExp(value, "gi"))
})
.show()
.length > 0;
if(value.length === 0 ) {
$persons.show().removeAttr('style');
}
if (!found) {
$persons.hide();
console.log("found nothing");
}
};

Replacing/Changing one value of an array with JQuery/Javascript

I have an array that is created within another Javascript call. The array is as follows:
HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,[" Accoun ","",1,0,1],[" Resources ","",1,0,1],[" Reworking ","",1,0,1],[" Account Services ","",1,0,1],[" Education ","",1,0,1],[" App ","",1,0,1]];
I am trying to replace just the '147' value at the top if another element is present within the HTML. So far I haven't had any luck.
This is the code I have been working with thus far.
$(document).ready(function (){
if ($('#impersonationWrapper').length > 0) {
var arr = HM_Array1;
var valChange = HM_Array1[0][2];
if (valChange !== -1) {
HM_array[valChange] = 202;
}
}
else {
}
});
The 147 corresponds to the value of the CSS 'top' value. Unfortunately I have to change this dynamically as I am not allowed to touch the old coding in place. Any help would be greatly appreciated.
I think you want:
var valChange = HM_Array1[0][2];
if (valChange !== -1) {
HM_Array1[0][2] = 202;
}
Your code
HM_array[valChange] = 202;
is the same as:
HM_array[HM_Array1[0][2]] = 202;
which is:
HM_array[147] = 202;
which is setting the value of the 147th item in HM_array as 202. Which isn't what you want. HM_array has only 1 item. And you want to set that item's 2nd item as 202 (replace 147 with 202).

Categories

Resources