javascript condition for session storage not working as expected - javascript

Currently working on session storage where user have to select one radio button from the first page and click next button div has to show in the second page in the first page i have created a function with set of objects where the data will be stored using set item in the second i am trying to get those value using get item.
I have two scenarios
When the user select pg radio button from the first radio group and if any location like alain / abudhabi if user select alain | abudhabi from the location from location then user slect DIP EDU if user click submit button then in the second page i need to get one check box and create application button the rest should be hide -- With my code this was working
If the user select ug radio button from the first radio group and if any location like alain / abudhabi if user click submit button then in the second page I need to get Just a Pay button but this was not working kindly help me
Here is my plunker link just like fiddle
This is what my code for to get the item from the first page
function storedata(){
var storeDate = {};
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
storeDate['storedValue2'] = $('#alain').prop('checked'),$('#abudhabi').prop('checked');
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
sessionStorage.setItem('storeDate', JSON.stringify(storeDate));
}
function storedata1(){
var storeDate1 = {};
storeDate1['storedValuej'] = $('#slt_mjr option:selected').val("Bachelor of Arts in Persian").text();
sessionStorage.setItem('storeDate1', JSON.stringify(storeDate1));
console.log(storeDate1);
}
When i checked in session storage I am getting the storedValue2 as false
After providing or in this line
storeDate['storedValue2'] = $('#alain').prop('checked') || $('#abudhabi').prop('checked');
I am getting true in the storedValue2 = true but my output was not working as expected
In the second page
var otherObj = JSON.parse(sessionStorage.getItem('storeDate'));
var otherObj1 = JSON.parse(sessionStorage.getItem('storeDate1'));
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 != "pg") {
$(".pay_check,.pay_click").show();
$(".pay_trans").hide();
} else if (otherObj1.storedValuej === "BAP") {
$('.create_btn,.no_applica').show();
$('.pay_btn').hide();
} else { * * // I have tried using like this but no use**
//$('.create_btn,.no_applica,.pay_click').hide();
$('.pay_btn').show();
}
any suggestion guys for the question
Kindly please guide me where I am doing wrong. Thanks in advance

Okay so you have a number of problems here. Mostly due to a misunderstanding of functions.
First of all, we can change
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
// to
storeDate['storedValue1'] = $('#pg').val();
The $ function provided by jQuery selects elements based on a given selector. So $('#pg') selects the element with the id pg. Then val() returns the value of the element.
Secondly, we need to change
storeDate['storedValue2'] = $('#alain').prop('checked'),$('#abudhabi').prop('checked');
// to
storeDate['storedValue2'] = $('#alain').prop('checked') || $('#abudhabi').prop('checked');
You're just misunderstanding boolean operators here. a || b resolves to true if a or b resolves to true.
And finally the worst offender
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
// to
storeDate['storedValue3'] = $('#slt_mjrpg).val();
val returns the value of an element. In the case of a select, it will return the value of the selected option. Providing a string parameter will set the value. So what we're doing instead is just getting the value, and we'll check the value later.
In your hide/show function, we don't need to change very much. We're just going to move that inappropriate val parameter down here in an equality operation to get a boolean value.
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 === "Dip - Prof. PG Dip in Teaching")

i think session storage is working with only one page.
You should try localstorage instade of sessionstorage.
Try this
function storedata(){
var storeDate = {};
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
storeDate['storedValue2'] = $('input[id=alain]:checked').val();
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
localStorage.setItem('storeDate', JSON.stringify(storeDate));
}
and
var otherObj = JSON.parse(localStorage.getItem('storeDate'));
var otherObj1 = JSON.parse(sessionStorage.getItem('storeDate1'));
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 !="pg") {
$(".pay_check,.pay_click").show();
$(".pay_trans").hide();
} else if (otherObj1.storedValuej === "BAP"){
$('.create_btn,.no_applica').show();
$('.pay_btn').hide();
} else {
**// I have tried using like this but no use**
//$('.create_btn,.no_applica,.pay_click').hide();
$('.pay_btn').show();
}

Related

Not able to correctly filter data using cascading multi select dropdown Syncfusion

I am using multi select dropdown with dependent dropdowns like below
Populating these list via api. Now if i select one value i am calling (change) function of angular to get the id of the dropdown and then calling a function to change other dropdown values.
OnChangeair(e){
if(e.element.id=='airid')
this.filterAirId(this.airIDModel)
else if(e.element.id=='airlead')
this.filterLead(this.airLeadModel)
else if(e.element.id=='airmd')
this.filterManagingDirector(this.airManagingDirectorModel)
else if(e.element.id=='airmanager')
this.filterManager(this.airManagerModel)
else if(e.element.id=='airaim')
this.filterAIM(this.airAIMProjectNameModel)
else if(e.element.id=='airse')
this.filterServiceArea(this.airServiceAreaModel)
}
Function to change the list is
filterAirId(airid){
if(airid.length == 0){
this.getAIRData();
}
else{
let finalArr = [];
airid.forEach((item)=>{
var name = this.airData.filter( el=>el.AIRID == item );
this.airData.push.apply(finalArr,name);
});
this.airManagingDirectorData=finalArr;
this.airServiceAreaData = finalArr;
this.airLeadData = finalArr;
this.airManagerData = finalArr;
this.airAIMProjectNameData = finalArr;
console.log(finalArr);
}
//this.assetData = this.assetData.filter((item) => item.AIRID == airid);
}
Now this works when i select any one of them others get correctly populated. But when i select another field the previous one's field gets replaced and my change event gets fired continuously resulting in
Angular HTML
<ejs-multiselect id='airid' (change)="OnChangeair($event)" [(value)]="airIDModel" [dataSource]='airIDData' [fields]='airIdFields' [allowFiltering]='true' [placeholder]='airIdPlaceholder'></ejs-multiselect>
<ejs-multiselect id='airmd' (change)="OnChangeair($event)" [(value)]="airManagingDirectorModel" [dataSource]='airManagingDirectorData' [fields]='airManagingDirectorFields' [allowFiltering]='true' [placeholder]='airManagingDirectorPlaceholder'></ejs-multiselect>
This picture shows all AIR id but the list keeps on flickering. I think it keeps on changing the list due to the change event.
Any help would be appreciated. Thank you

How I can use that code with two dropdown menus?

How I can use that code with two dropdown menus? Actually when I reload the page the first dropdown menu stays like I want but the second one no. Thanks. Sorry to ask, Im new in all this incredible world!
var init = function () {
strong text
var sel = $("select"),
but = $("button");
var clearSelected = function () {
sel.find(":selected").prop("selected", false);
};
if (localStorage.getItem("pref")) {
var pref = localStorage.getItem("pref");
clearSelected();
//set the selected state to true on the option localStorage remembers
sel.find("#" + pref).prop("selected", true);
}
var setPreference = function () {
//remember the ID of the option the user selected
localStorage.setItem("pref", sel.find(":selected").attr("id"));
};
var reset = function () {
clearSelected();
localStorage.setItem("pref", undefined);
};
sel.on("change", setPreference);
but.on("click", reset);
};
$(init);
**strong text**
I think .filter is what your need here. See this
.find will return the first element it founds that responds to the criteria you give. That's why your first dropdowm list is correct and not the second.
Also, for your storage, I guess you have 2 choices:
Set an item for the first dropdown menu, and another one for the second one that you can handle separatly.
Set only one item but containing an array of the values selected. With this solution you would have to set the item with an object as so
Hope I helped.
EDIT
I think this should do the math

Javascript catch unselected radio button along with textboxes and alert

I'm practically new here and i'm a beginner in programming.
I am creating an html/js based template for my team for easy consolidation of data and copy to clipboard so we can easily paste it in our main tool.
The problem is that doesn't seem to work properly (at least here at the office, at home it does work).
It doesn't prompt when the radio selection is empty, so I am resorting to using my current function that catches any textboxes/textarea that is empty. (sample code below)
if (document.getElementById('INbrief').value == "") {
errCatch +="-Issue/Request \n";
valid = false;
}
if (document.getElementById('INdesc').value == "") {
errCatch +="-Issue/Request Description \n";
valid = false;
}
if (!valid) {
document.body.removeChild(dummyTxtArea);
alert(errCatch);
return valid;
} else {
document.body.removeChild(dummyTxtArea);
alert ("Data has been copied to Clipboard.");
}
The above if else is inside a Function that is called when the Evenlistener is triggered via "click" of the submit button. I tried inserting a 'for' statement above the if else inside the function but it wont work and the alert will only show that the textbox/area are empty. Thanks in advance for your help
Your code was throwing errors at lines 4 and 5 when you were trying to get the value of an unchecked radio box and set the variable to that value:
var selectedLOB = document.querySelector('input[name="INlob"]:checked').value; //LOB selected
var selectedSev = document.querySelector('input[name="INsev"]:checked').value; //Severity selected
In order to fix this you must first check if the radio is selected, and then if it is get the value that is selected. You can do that by replaceing your lines 4 and 5 with the following:
var selectedLOB = document.querySelector('input[name="INlob"]:checked') ? document.querySelector('input[name="INlob"]:checked').value :false;
var selectedSev = document.querySelector('input[name="INsev"]:checked') ? document.querySelector('input[name="INsev"]:checked').value :false;
This code will first check to see if the radio is checked, if it is it will set the variable to the value, if it is not it will set the variable to false.
(The a ? b : c is know as the conditional or ternary operator and is just a short if() else()statement). This change will stop the errors from being thrown.
You will also need to update your checks further down for the radios to:
if (selectedLOB == false) {
errCatch +="-Choose LOB \n";
valid = false;
}
if (selectedSev == false) {
errCatch +="-Choose Severity \n";
valid = false;
}
As a side note you don't have to set uncheck radios to false, you could set them to a string like 'unchecked' or ''empty' if it helps make your code more readable. Just be sure to make sure that your checks match what you set it to.

Bootstrap form group checkboxes doesn't get checked in between nav pills

Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/
I use Bootstrap nav-pills to show all products and categorized too like this:
And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes
I count the number of products checked in between the tabs like this:
jQuery(document).ready(function($) {
jQuery(".select-product").change(function() {
jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);
});
});
But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.
I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.
Ideas, anyone?
Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.
Before we try and resolve this issues, we should break it down and see what the actual problem is.
First, let's check if we remove the content from tab 1b is the issue still present?
Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.
Fiddle #1
What if we change the id of the checkboxes (remember ids should be unique).
Notice how Book #1 now works if we change the first checkbox's id to 1a.
Fiddle #2
So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:
How do we check multiple checkboxes if one is checked
(or something like that)
Here's what I would do:
assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison
Working Example
EDIT
Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.
var productIDs = <?php echo json_encode($products_id_array) ?>;
and then creating the snippet of jQuery code on the fiddle like this
productIDs.forEach(function(val, key) {
jQuery('.' + val).on('change', function(){
jQuery('.' + val).prop('checked',this.checked);
});
})
Try this JS, This will work
jQuery(".select-product").change(function() {
var checkValue = jQuery(this).prop('checked');
$('.select-product#' + jQuery(this)[0].id).each(function() {
if (checkValue == true) {
jQuery(this).prop('checked', true)
} else {
jQuery(this).prop('checked', false);
}
});
var uniqueId = [];
jQuery("[type='checkbox']:checked").each(function() {
uniqueId.push(jQuery(this)[0].id);
});
Array.prototype.getUnique = function() {
var u = {},
a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
jQuery(".counter").text(uniqueId.getUnique().length);
});

Clear a form and populate jquery

I am trying to clear a form and then repopulate it with new data. I have a page that has a list of search histories, along with a "search again" button, when clicked, it takes that search history string, split it, then match those again all the various form items; checkbox, radio, etc. The form has basically every kind of form element in it and everything is populating like I want it to except the checkboxes. The first time I click the populate form button, it works fine, but after the first click all the checkboxes start going haywire...some items populating like they should, some not, in a strange random pattern. I have not included the html because I don't think it is necessary but if anyone needs more info, please let me know.
This resets the form. I have tested this independently and it works.
function form_reset(){
$('#hosp_search_form')[0].reset();
$('#hosp_search_form').find("input[type=text], textarea").val("");
$('input[type=checkbox]').each(function(){
$('input[type=checkbox]').removeAttr('checked');
});
$('input[type=number]').val('');
$('input[type=radio]').each(function(){
$(this).removeAttr('checked');
});
On click, first clear the form of previous values, then grab the other needed values and format them...this part gets a little ugly in sections but I have consoled out all the values and everything is how it should be.
$('.search_again_btn').on('click', function(){
form_reset();
$('#hosp_search_form').find('input[type=checkbox]').removeAttr('checked');
var id = $(this).data('id');
var searchstring = $('#searchstring_' + id).text();
var patientcode = $('#patientcode_' + id).text();
var mrn = $('#mrn_' + id).text();
var first_name = patientcode.substr(0,2);
var last_name = patientcode.substr(2,2);
var age = patientcode.substr(4,3);
var gender = patientcode.substr(6,2);
var age = age.replace(/\D+/g, '');
gender = gender.replace(/[0-9]/g, '');
Populates some of the form, works fine
//populate fields in search form
$('input[name=fn]').val(first_name);
$('input[name=ln]').val(last_name);
$('input[name=patientage]').val(age);
$('input[name=mrn]').val(mrn);
Populate another part of the form, also always works as needed
//populate gender fields
if(gender == 'F'){
$('.female').attr('checked', 'checked');
}
if(gender == 'M'){
$('.male').attr('checked', 'checked');
}
Here is where I suspect the issue is. splitsearch is a long string (a previous search history) with items separated by a . and they get split into separate items. I console logged this, it correctly breaking it into the smaller values like I need, then iterate through those and iterate through all the checkboxes which each have a data attr holding values that can be in the splitsearch. If a value matches, it should make it checked. This works every time the first time, for any combo of splitsearch/search string values, but after the first time, I don't know what it is doing. I expect that each click, the form is cleared and it does the value matching again as I described.
//populate checkboxes
var splitsearch = searchstring.split('. ');
$.each(splitsearch, function(key, value){
$('input[type=checkbox').each(function(keyb, checkbox){
item = $(checkbox).data('services');
if(item == value){
$(this).attr('checked', 'checked');
console.log($(this));
}
});
This is doing the same as the above but works every time...probably because there is never multiple combinations like with checkboxes.
$('input[name=payor]').each(function(k, radio){
if(value == $(radio).data('payors')){
$(this).attr('checked', 'checked');
//console.log($(this));
}
});
Also like the above and works.
$('input[name=bedtype]').each(function(keyc, radio){
bed = $(radio).data('bed');
if(bed == value){
$(this).attr('checked', 'checked');
}
});
This part below is quite ugly but is populating the form like I need every time.
//if searchstring contains Needs Transportation, returns true, else returns false
if(value.indexOf("Needs Transportation") > -1 === true){
$('.transyes').attr('checked', 'checked');
}
if(value.indexOf("Near hospital") > -1 != true){
$('input[name=desiredzip]').val(searchstring.substr(5,5));
}
if(value.indexOf("5 mile radius") > -1 === true){
$('.miles_5').attr('checked', 'checked');
}
if(value.indexOf("10 mile radius") > -1 === true){
$('.miles_10').attr('checked', 'checked');
}
if(value.indexOf("15 mile radius") > -1 === true){
$('.miles_15').attr('checked', 'checked');
}
if(value.indexOf("20 mile radius") > -1 === true){
$('.miles_20').attr('checked', 'checked');
}
});
Scrolls the window up to the populated search form and show it.
window.scrollTo(0,100);
$('#search_show').show();
});
Just a thought but, it might help you to restructure your code a bit to keep it DRY.
// used to Hold search data in local or global
var data;
function form_reset() {
// clear form
}
function get_search_data() {
// populate data with search results
}
function form_populate() {
// use data to populate form
}
$('.search_again_btn').on('click', function(){
get_search_data();
form_reset();
form_populate();
});
// Initial Load of form
get_search_data();
form_populate();
that way you use the same population function initially as you do when you refresh and it forces you to put your data into a variable that can be seen in both the clear and populate functions removing your reliance on this and $(this).
also you need to bear in mind that the value of this inside a click function is going to be in the context of the click event itself and not the JavaScript object that the rest of your code belongs to.

Categories