How to keep value of cshtml view object in javascript? - javascript

Inside the cshtml view I have a dropdown list with 2 possible options. If selection returns "True", a container with 2 datepickers becomes visible, so user can select a daterange. Whenever I switch dropdown option, both datepickers are assigned with respective values.
$("#ExpirationChoice").change(function () {
var val = $(this).val(); //picks up either True or False
if (val) {
if (val === "True") {
$("#expirationDates").show(); //show container with datepickers
$("#BeginDate").val(getFormattedDate(today()));
$("#EndDate").val(getFormattedDate(today().addMonths(6)));
}
else {
$("#expirationDates").hide();
$("#BeginDate").val("");
$("#EndDate").val(getFormattedDate(today()));
}
}
else {
alert("Please select an option of past or future expiration report.");
}
});
Let's assume I picked True from dropdown, selected a 1 month range between 12/23/16 and 01/23/17, clicked the button to generate a table.
Then, I switched dropdown option to False, which caused to hide container and reassign date values to empty and today in datepickers (hidden, thus, can't be controlled by user).
Now, when I switch back to True again, my selections are gone, it again assigns it to a 6-month range (I understand why it does it, I will explain my attempts later).
My question is: How to keep my latest selections from True option whenever I switch?
A challenge through my attempts
I understand exactly why it was behaving the following way. My way of thinking is to store selections of datepickers from True option into variables. However, here is a challenge that I am suddenly running into:
if (val === "True") {
$("#expirationDates").show();
$("#BeginDate").val(getFormattedDate(today()));
$("#EndDate").val(getFormattedDate(today().addMonths(6)));
var start = $("#BeginDate").val();
var end = $("#EndDate").val();
}
I need to initially assign dates to be a 6-month daterange. So far variables store dates properly. However, whenever I switch, date values will be reassigned back to 6 month range, and it turns into an infinite loop.
Pretty much, I would appreciate any direction in terms of the better approach for such problem.

use a flag var
var flag = false; //global variable
var start;//global variable
var end;//global variable
if (val === "True") {
$("#expirationDates").show();
if(flag == false){
$("#BeginDate").val(getFormattedDate(today()));
$("#EndDate").val(getFormattedDate(today().addMonths(6)));
}
else {
$("#BeginDate").val(start);
$("#EndDate").val(end);
}
start = $("#BeginDate").val();
end = $("#EndDate").val();
flag = true;
}

The main challenge of my case was getting an updated value from datepickers. After doing some additional research, I found this post as a hint to resolve my issue. Therefore, instead of getting latest values from .change(), I stored necessary values on .click()
$("#btnExpiringUnitsTable").click(function () {
var e = document.getElementById("ExpirationChoice");
var selectedOption = e.options[e.selectedIndex].value;
//code
if (selectedOption === "True") { //store latest datepicker values in variables from "True" selection
start = $("#BeginDate").val();
end = $("#EndDate").val();
}
//code
});
As for my initial .change(function), it narrowed it down to the following:
$("#ExpirationChoice").change(function () {
var val = $(this).val();
if (val) {
if (val === "True") {
$("#expirationDates").show();
$("#BeginDate").val(start);
$("#EndDate").val(end);
}
else {
$("#expirationDates").hide();
$("#BeginDate").val("");
$("#EndDate").val(getFormattedDate(today()));
}
}
else {
alert("Please select an option of past or future expiration report.");
}
});
From what I see, I will not be able to pick up updated values from .change(), I would have to go with .click().

Related

Correlating a Row with Column on Javascript

I currently have a table with a function that checks certain columns that have checkboxes, whenever they are "clicked off", to see if they're all completely empty.
The function does a loop from the first of the checked columns up until the last one that has to be checked. They go from 1 to 8, and their ids go from "f01_check" up until "f08_check". If all are empty, it adds a css class to its description column that changes background color.
The function looks like this:
function unChecked(rowNumber) {
alert(rowNumber);
var i = 1;
var check = false;
// Column loop
while (i < 9 && check == false) {
if (rowNumber.getElementById("f0" + i + "_check").checked == false) {
i++;
} else {
check = true;
}
// If all checkboxes are empty, add class
if (i == 9 && check == false) {
$s(description.addClass(emptyRecords));
}
}
}
The Dynamic Action leading to this function and its parameter is this:
var row = this.triggeringElement.closest('tr');
unChecked(row);
I realize that the rowNumber.getElementById doesn't work, but I can't figure out how to link or connect them. The way I'm looping through the columns might be a rough attempt, but it works. I've tested it on a set column and it it does stop whenever the loop reaches a checked checkbox. The problem is I just can't dynamically set the row to match the one that I've clicked.
I've tried getting the property .rowIndex as well, but I can't figure out where to use it, even if I do get the correct value.
I found a different solution, that also somewhat solves a different problem in the future.
Rather than use rownum to set a dynamic id for the columns, I changed it to it's primary key:
apex_item.checkbox (1, '1_' || pk, decode(data1,null,null,'CHECKED'), null, null, 'f01_' || pk) as lpb1
This basically helped me on knowing which row was being clicked, because the id also held it's primary key. This allowed me to use it's primary key value to improve the function. The item_pkis an item that gets its value from the corresponding table column:
function unChecked(row) { // var row = this.triggeringElement.closest('tr').rowIndex;
// unChecked(row);
var i = 1;
var check = false;
while (i < 9 && check == false) {
if (document.getElementById("f0" + i + "_" + item_pk.value).checked == false) {
i++;
} else {
check = true;
}
if (i == 9 && check == false) {
//addClass Segment
}
}
}
So if the report were to be filtered, the row number wouldn't match what the filter actually showed on the report table.
The previous solution was also fixed by removing the case clause from the select, as follows:
apex_item.checkbox (1, '1_' || a.pk, case when max(decode(data1,1,1,null)) is null then '' else 'CHECKED' end, null, null, 'f01_chk') as lpb1,
But again, the first solution showed actually foresees and handles a filtered report, so I believe it's a superior and more accurate solution.
Now I just need to complete the addClass segment. For some reason Apex is setting the field "static id" as the column header, which is slightly problematic since I meant to use the document.getElementById. But at least the main problem has been fixed. Thanks for the responses.

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.

Looping through a ASP.NET Listbox with Javascript not working

I'm trying to loop through an ASP.NET listbox with Javascript, but I'm getting a null object or undefined when it hits the lboxRight variable in the for loop. Here's what I have.
function save() {
var containsTypeA = false;
var containsTypeB = false;
var containsType = false;
var lboxRight = $get('<%=lboxRight.ClientID %>').value;
if (lboxRight != null) {
for (var i = 0; i < lboxRight.options.length; ++i) {
if (lboxRight.options[i].value == "Type A") {
containsTypeA = true;
}
if (lboxRight.options[i].value == "Type B") {
containsTybeB = true;
}
}
containsType = true;
}
}
There's an onclick event mapped to when the save button is pressed that calls this function. Am I doing this the right way to look at the listbox and tell me if it has this specific value in it? My intention is for the listbox to contain Type A as a value and then when it loops through the listbox, if it finds that value within the list it will set that variable to true for some other logic. Visual Studio seems to complain about the for loop line, what am I doing wrong here? I am using the exact same loop written elsewhere and it works fine, so I am not understanding why this one isn't working.
Is there anything wrong with this as I have written it?
If it is complaining about something being null or undefined on the for loop line I would check to see what lboxRight.options is since you already check lboxRight.
Actually it wouldn't make sense for options to exist since lboxRight is being set to the value of the select not the select.
Try changing
var lboxRight = $get('<%=lboxRight.ClientID %>').value;
to
var lboxRight = $get('<%=lboxRight.ClientID %>');

jQuery grep return on Multidimensional Array

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);
});

Firefox ignores selected option, always displays last item in dropdown

So I've written some code to sort all my site's select menus, and it works perfectly in every browser we support... except Firefox.
http://jsfiddle.net/vkjAC/6/
My code takes in the options for a select element, sorts them, and returns them. Somewhere in there, the selectedIndex on the select element changes to the last item.
I check what values are selected/defaultSelected:
for(k=0; k<options.length; k++)
{
if(options[k].defaultSelected == true)
{
sel = k;
break;
}
}
if(sel === null)
{
for(k=0; k<options.length; k++)
{
if(options[k].selected == true)
{
sel = k;
break;
}
}
}
if(sel === null)
{ options[0].selected = true; }
else
{ options[sel].selected = true; }
But I can't set the selectedIndex from this function because I'm not passing in the entire select object, just the option list.
I tried looking up similar problems, but every other thread I saw said it was a caching problem, or that I needed to add autocomplete="off", but those didn't work. I assume it has something to do with my code, but I haven't modified the selectedIndex property anywhere.
Any suggestions? I'm losing my mind (and running out of time!)
I've had this before. It has something to do with the fact that the options are removed then added again. You have to re-select the value after sorting. For example:
var ops = $('#mass').find('option');
$('#mass').prepend(sortDropDown(ops)).val($("#mass > option[selected]").val());

Categories

Resources