What is causing the for-loop to function correctly in the console but not in my Helper?

I'm facing a challenge with my code. When I execute this specific code snippet in the Chrome console, it works fine as intended. However, when the same code runs in the application, it doesn't perform as expected.

The purpose of this code is to compare the elements in the selectedItemIDSet array with the elements in the TotalOfallIds array. If there's a match, it should display a "Yes" message, otherwise a "No" message.

 var selectedItemIDSet = Session.get('selectedItemIDSet'); 
 console.log(selectedItemIDSet);

The console.log() output for the above code snippet is:

["GttzCQLzMeqj", "yzML7ZLvkWkjBBvq5", "2HwJhHyjDhDogJK"]

var TotalOfallIds =  buyList.find().fetch().map(function(u) { return u._id; });

console.log (TotalOfallIds);

The console.log() output for this snippet is:

EkebEek7KH8mdpNXg,LZJKA8S3wYNwHakzE,ikrbCDuttHrwkEcuv, yzML7ZLvkWkjBBvq5,e72HwJhHyjDhDogJK,GttzCQLzMeqjJP4Ae, XzGxS3LDtJ4DrXSdc,FJDhf7mzCxX4CKThe,TaTg6hf3Gok5NsWYp, NhDXRMnLWpwfAkWzJ,nG9TsoScYGFbEuerr,8CdapJoeSxSScHKFs, EsjSJfSgatrYTEnDK

 var noOfloops = selectedItemIDSet.length;
 var selectedItemId = this._id;
 var allclicked;

for(var i = 0; i < noOfloops; i++ ) {
var clickedImg = selectedItemIDSet[i];
allclicked = TotalOfallIds.indexOf(clickedImg) > -1; 

console.log("May: " +allclicked);
    if (allclicked == 1 ) {
        alert("Yes! " );
    //  return "selectedItem";
        }
   else {   
    alert("No! ");
    //return "";
    }}

Although it functions correctly in the console, the issue arises in the template helper where the loop seems to iterate (three times) over the selectedItemIDSet array and (13 times) over all properties of TotalOfallIds. Additionally, it only checks the GttzCQLzMeqj property against TotalOfallIds!

This inconsistency is perplexing to me!

Below is the code from my template helper:

'selectedItem' : function () {     

       var selectedItemIDSet = Session.get('selectedItemIDSet');
        var TotalOfallIds =  buyList.find().fetch().map(function(u) { return u._id; });
        var loops = selectedItemIDSet.length;
        var selectedItemId = this._id;      
        var allclicked = true;

    for(var i = 0; i < loops; i++ ) {
    alert("Checking..." + selectedItemIDSet[i]+ " in " +TotalOfallIds);
    var clickedImg = selectedItemIDSet[i];
    allclicked = TotalOfallIds.indexOf(clickedImg) > -1; 

        if (allclicked == 1 ) {
            alert("Yeeeeiiiii! " );
            return "selectedItem";      
            }
       else {   
        alert("Nnoooooo! ");
        return "";
        }


    }

}, 

Apologies for the lengthy description!

Any assistance would be highly appreciated.

Answer №1

After some troubleshooting, I managed to solve the issue by updating the if condition code. Initially, it was set as if (allclicked == 1 ), but I changed it to

if (selectedItemId.indexOf(clickedImg) != -1)
. Oddly enough, the code worked when tested in the console, yet failed to produce the desired outcome in the actual project.

Therefore, the revised and functional if condition code is:

if (selectedItemId.indexOf(clickedImg) != -1) {
    alert("Yes! " + clickedImg);
    return "selectedItem";
} else {
    // alert("No!");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Empower your ASP.NET application by illuminating the textbox upon text modification

Could there be a solution to persistently highlight textboxes after their content has been changed on an asp.net form? Currently, I am utilizing jquery for this purpose, but the highlighting disappears following a postback in asp.net. Is there a method t ...

Modify the background of a DIV upon clicking it

Is there a way to achieve the following scenario: I have multiple DIVS <div style="background-color: black;">text1</div> <div style="background-color: black;">text2</div> <div style="background-color: bl ...

Creating a dropdown menu in React

Imagine having an options array like the one below: options = [ { name: 'My profile' }, { name: 'Sign out' } ] public selectOptions(showOptions: boolean) { this.setState({ showOptions: !showOptions }) return options.map((opt ...

Transforming an array of HTTP Observables into an Observable that can be piped asynchronously

I am attempting to execute a series of XHR GET requests based on the results of an initial request. I have an array of observables representing the secondary requests I wish to make, and I am able to utilize Array.map for iterating over them and subscribin ...

What is the best way to initiate a fresh AJAX request whenever the submit button is pressed?

Every time the submit button is clicked on my form, a modal appears and gets filled with JSON data from the application /addresschecker. If I receive an error message with a code return number of 2003, it indicates an issue with the addresses provided. Oth ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Encountering an error while using $state.go function in Angular JS testing

Below is the code snippet for a Controller in Angular JS: describe('Controller: homeCtrl', function () { beforeEach(module('incident')); var homeCtrl, $state; beforeEach(inject(function ($controller, _$state_) { $state = _ ...

React Component being mounted and unmounted several times in the same session

Every time I switch between two tabs in my React app, the useEffect function is triggered to call the API. Is it acceptable to call the API every time the page mounts, or should it only be done on the initial mount? If we only call the API on the first mo ...

Saving information using Socket.io server during the 'connect' event

Currently, I am working with socket.io along with MongoDB and promises. My goal is to save some data in Mongo when the session is established so that further socket events cannot be properly handled until this data is successfully saved. // Below is my si ...

Tips for removing residue from old watches

Our angularJS web components are integrated with a jqxGrid. Whenever a user makes edits in a cell, we implement a custom typeahead editor using Angular. However, I have noticed that after the editor is destroyed, my $watches array does not revert back to i ...

What is the best way to save personalized CSS styles into a database?

Appreciation for assisting others and contributing to open source projects. I have developed a Vue.js to-do application that stores data in Firebase using vue-fire and Firestore. One issue I am experiencing is that the styling, such as "line-through" for ...

Please ensure that only numerical values and decimal points are allowed

Hello there, I am currently developing a directive in AngularJS that specifically allows only positive numbers and decimal values. Any characters other than numbers (such as +, -, abc...) will be removed from the input. Initially, I attempted to achieve t ...

The <span> tag with content-editable attribute loses selection when the mouse button is released

I'm attempting to utilize a content-editable span tag as an inline text input box with variable width. Everything is functioning properly, except for the issue of not being able to select the entire text when focusing on the box. When tabbing to the e ...

Can the chosen date in a calendar date picker be linked to a variable that is accessible to a separate file?

Currently, I am developing a React application and have integrated a date picker feature using Ant Design to enable users to select a date range. My goal is to store the selected date value into a variable that can be accessed by another file in my progr ...

Tutorials on transferring selected option data to a component

My JSON data is structured like this: Whenever I choose an option, I want to pass the values (code and description) from the JSON object to the component. nameList= [ { "code": "1", "description": "abc" }, { "code": "123", "descript ...

Proper method to refresh a blog post that has undergone revisions

Good evening, everyone. I almost have my site ready for testing, just one last piece to go! I'm struggling with the correct way to do this. Currently, I am working on a blogging CMS of sorts. I display blog posts in individual divs, each containing ...

The submit button is unresponsive and does not react to any actions

Encountering a peculiar issue! My submit button is not responding to the action. Here is the code snippet in question: <script type="text/javascript"> function save_contact_information() { document.getElementById('User_Finder&apos ...

Exploring Three.js: Implementing Multiple Textures for Points

I'm currently working on a Three.js project where I want to incorporate multiple points with different textures. However, I've encountered an issue with changing textures in my fragment shader. Despite setting up the scene so that points should s ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

The 'gulp-jade' plugin seems to be malfunctioning and failing to properly compile jade files into HTML documents

Currently, I am immersed in a project where I rely on using gulp. My main objective is to compile the jade files I create (found in the _jadefiles folder) and have them output as .html files in the _includes folder within my project. The current list of t ...