Verifying the accuracy of a selector in JavaScript may encounter operational issues

There are multiple divs in my HTML code with different background images. When a div is clicked, a selector is set to true. For instance, if the "jogging" div is clicked, the background color changes from black to orange and the jogging_selected selector is set to true.

Now, I have added a next button (#button_step3) that should hide this section only if one of the divs is selected.

The issue is that it always triggers the "else part" even when a selector is true, and I can't figure out why.

UPDATE

Upon adding console.log(jogging_selected); to the else part of the if query, it logs false. This confuses me because when I click the div again, the color changes back to black, indicating that the selector is true.


Below are the relevant parts of my JavaScript, CSS, and HTML code:

$(document).ready(function() {    
      
  var jogging_selected = false;
  var soccer_selected = false;
  var tennis_selected = false;
  var golf_selected = false;
    
  function setBackgroundAndSelector(childnumber, imagepath_black, imagepath_orange, activity_selector){
    if(activity_selector){
      $(childnumber).css( "background", imagepath_black)
    }
    else{
      $(".image_activitys:nth-child(1)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging)" );
      $(".image_activitys:nth-child(2)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer)" );
      $(".image_activitys:nth-child(3)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis)" );
      $(".image_activitys:nth-child(4)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Golf)" );
      jogging_selected = false;
      soccer_selected = false;
      tennis_selected = false;
      golf_selected = false;
      for(i=1; i<5; i++){
        if('.image_activitys:nth-child('+i+')' == childnumber){
          $(childnumber).css( 'background', imagepath_orange );
        }
      }
      activity_selector = true;
    }
    activity_selector = !activity_selector
   }
      
   $(".image_activitys:nth-child(1)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(1)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Jogging)", jogging_selected);
   });
    
   $(".image_activitys:nth-child(2)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(2)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Soccer)", soccer_selected);
  });
    
  $(".image_activitys:nth-child(3)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(3)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Tennis)", tennis_selected);
  });
    
  $(".image_activitys:nth-child(4)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(4)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Golf)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Golf)", golf_selected);
  });
      
  // The problematic function
      
  $("#button_step3").click(function() {
    if(jogging_selected || soccer_selected  || tennis_selected  || golf_selected){
      $("#wrapper_fitcalc_content_step2" ).css( "display", "none" );
      $("#wrapper_fitcalc_content_step3" ).css( "display", "block" );
    }
    else{
      window.scrollTo(0, 0);
      alert("Please select a sport");
      console.log(jogging_selected);
    }
  });
});
.image_activitys{
margin: 5px;
width: 128px;
height: 128px;
}

.image_activitys:nth-child(1){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging); 
}
.image_activitys:nth-child(1):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Jogging) !important;
  cursor: pointer;
}
.image_activitys:nth-child(2){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer);
}
.image_activitys:nth-child(2):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Soccer) !important;
  cursor: pointer;
}
.image_activitys:nth-child(3){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis);
}
.image_activitys:nth-child(3):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Tennis) !important;
  cursor: pointer;
}
.image_activitys:nth-child(4){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Golf);
}
.image_activitys:nth-child(4):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Golf) !important;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div id="wrapper_fitcalc_content_step2">
      
  <div class="image_activitys" title="Jogging"></div>
  <div class="image_activitys" title="Soccer"></div>
  <div class="image_activitys" title="Tennis"></div>
  <div class="image_activitys" title="Golf"></div>
          
  <!-- There are several more of this divs which I just deleted for my post -->
      
  <input type="button" value="to Step 3" id="button_step3"/>
      
</div>

Can anyone help me understand why he always goes to the else part in the $("#button_step3").click(function())?

Answer №1

When utilizing boolean variables in a function, they are passed by value and not by reference. In this scenario, the fourth argument of the function setBackgroundAndSelector passes the boolean variables by value. As a result, the original variables (jogging_selected, soccer_selected, tennis_selected, golf_selected) remain unchanged after the function is executed, with only copies being modified. Here's an alternative solution:

var selection={jogging_selected: false,
soccer_selected :false;
tennis_selected : false;
golf_selected : false};
function setBackgroundAndSelector(childnumber, imagepath_black, imagepath_orange, activity_selector){
    if(selection[activity_selector]){
        $(childnumber).css( "background", imagepath_black)
    }
    else{
        $(".image_activitys:nth-child(1)").css( "background", "url(jogging_black.png)" );
        $(".image_activitys:nth-child(2)").css( "background", "url(soccer_black.png)" );
        $(".image_activitys:nth-child(3)").css( "background", "url(tennis_black.png)" );
        $(".image_activitys:nth-child(4)").css( "background", "url(golf_black.png)" );
        jogging_selected = false;
        soccer_selected = false;
        tennis_selected = false;
        golf_selected = false;
        for(i=1; i<5; i++){
            if('.image_activitys:nth-child('+i+')' == childnumber){
                $(childnumber).css( 'background', imagepath_orange );
            }
        }
        selection[activity_selector] = true;
    }
    selection[activity_selector]= !selection[activity_selector]
}

$(".image_activitys:nth-child(1)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(1)", "url(jogging_black.png)", "url(jogging_orange.png)", "jogging_selected");
});

$(".image_activitys:nth-child(2)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(2)", "url(soccer_black.png)", "url(soccer_orange.png)", "soccer_selected");
});

$(".image_activitys:nth-child(3)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(3)", "url(tennis_black.png)", "url(tennis_orange.png)", "tennis_selected");
});

$(".image_activitys:nth-child(4)").click(function () {
    setBackgroundAndSelector(".image_activitys:nth-child(4)", "url(golf_black.png)", "url(golf_orange.png)", "golf_selected");
});


// Issue with this Function

$("#button_step3").click(function() {
    if(selection["jogging_selected"] || selection["soccer_selected"]  || selection["tennis_selected"]  || selection["golf_selected"]){
        $("#wrapper_fitcalc_content_step2" ).css( "display", "none" );
        $("#wrapper_fitcalc_content_step3" ).css( "display", "block" );
    }
    else{
        window.scrollTo(0, 0);
        alert("Please select a sport");
    }
});
});

Answer №2

There are 4 variables that will never be set to true:

var jogging_selected = false;
var soccer_selected = false;
var tennis_selected = false;
var golf_selected = false;

This is because you are only modifying the value of the parameter activity_selector which is local to the function setBackgroundAndSelector. Once the function finishes execution, the value of activity_selector is lost. To achieve a "call-by-reference" behavior where modifying activity_selector affects the boolean variable passed in (e.g.,

golf_selected</code), you need to use "call-by-value" in JavaScript.</p>

<p>To work around this issue, consider using a global variable for state as shown in the code snippet below:</p>

<p><div>
<div>
<pre class="lang-js"><code>$(document).ready(function() {    

    var sport_selected = {};

    function setBackgroundAndSelector(childnumber, imagepath_black, imagepath_orange, activity_selector){
        // Function implementation
    }

    // Event listeners for each image_activitys element

    // Step 3 button click event listener

});
.image_activitys{
margin: 5px;
width: 128px;
height: 128px;
}

/* CSS rules for image_activitys elements */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div id="wrapper_fitcalc_content_step2">
      
  <div class="image_activitys" title="Jogging"></div>
  <div class="image_activitys" title="Soccer"></div>
  <div class="image_activitys" title="Tennis"></div>
  <div class="image_activitys" title="Golf"></div>
          
  <input type="button" value="to Step 3" id="button_step3"/>
  
  <!-- Additional divs removed for brevity -->
      
</div>

Answer №3

If you're looking for a solution, give this code a shot!

$(document).ready(function() {    
      
  var jogging_selected = false;
  var soccer_selected = false;
  var tennis_selected = false;
  var golf_selected = false;
    
  function setBackgroundAndSelector(childnumber, imagepath_black, imagepath_orange, activity_selector){
    if(activity_selector){
      $(childnumber).css( "background", imagepath_black)
      return !activity_selector;
    }
    else{
      $(".image_activitys:nth-child(1)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging)" );
      $(".image_activitys:nth-child(2)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer)" );
      $(".image_activitys:nth-child(3)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis)" );
      $(".image_activitys:nth-child(4)").css( "background", "url(http://dummyimage.com/128x128/000000/fff.png&text=Golf)" );
      jogging_selected = false;
      soccer_selected = false;
      tennis_selected = false;
      golf_selected = false;
      for(i=1; i<5; i++){
        if('.image_activitys:nth-child('+i+')' == childnumber){
          $(childnumber).css( 'background', imagepath_orange );
        }
      }
      return true;
    }
    return !activity_selector;
   }
      
   $(".image_activitys:nth-child(1)").click(function () {
    jogging_selected = setBackgroundAndSelector(".image_activitys:nth-child(1)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Jogging)", jogging_selected);
   });
    
   $(".image_activitys:nth-child(2)").click(function () {
    soccer_selected = setBackgroundAndSelector(".image_activitys:nth-child(2)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Soccer)", soccer_selected);
  });
    
  $(".image_activitys:nth-child(3)").click(function () {
    tennis_selected = setBackgroundAndSelector(".image_activitys:nth-child(3)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Tennis)", tennis_selected);
  });
    
  $(".image_activitys:nth-child(4)").click(function () {
     golf_selected = setBackgroundAndSelector(".image_activitys:nth-child(4)", "url(http://dummyimage.com/128x128/000000/fff.png&text=Golf)", "url(http://dummyimage.com/128x128/ff9900/fff.png&text=Golf)", golf_selected);
  });
      
      
  // This is the function which does not work properly
      
  $("#button_step3").click(function() {
    if(jogging_selected || soccer_selected  || tennis_selected  || golf_selected){
      $("#wrapper_fitcalc_content_step2" ).css( "display", "none" );
      $("#wrapper_fitcalc_content_step3" ).css( "display", "block" );
    }
    else{
      window.scrollTo(0, 0);
      alert("Please select a sport");
    }
  });
});
.image_activitys{
margin: 5px;
width: 128px;
height: 128px;
}

.image_activitys:nth-child(1){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Jogging); 
}
.image_activitys:nth-child(1):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Jogging) !important;
  cursor: pointer;
}
.image_activitys:nth-child(2){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Soccer);
}
.image_activitys:nth-child(2):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Soccer) !important;
  cursor: pointer;
}
.image_activitys:nth-child(3){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Tennis);
}
.image_activitys:nth-child(3):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Tennis) !important;
  cursor: pointer;
}
.image_activitys:nth-child(4){
  background:url(http://dummyimage.com/128x128/000000/fff.png&text=Golf);
}
.image_activitys:nth-child(4):hover{
  background:url(http://dummyimage.com/128x128/ff9900/fff.png&text=Golf) !important;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div id="wrapper_fitcalc_content_step2">
      
  <div class="image_activitys" title="Jogging"></div>
  <div class="image_activitys" title="Soccer"></div>
  <div class="image_activitys" title="Tennis"></div>
  <div class="image_activitys" title="Golf"></div>
          
  <!-- There are several more of this divs which I just deleted for my post -->
      
  <input type="button" value="to Step 3" id="button_step3"/>
      
</div>

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

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

The animation named "fade1" is functioning properly, whereas "fade0" is not working as expected

Is there a way to incorporate animations into the "Forgot Password?" element using JavaScript? document.querySelectorAll(`button`).forEach(btn => btn.addEventListener(`click`, () => { if (btn.id === 'login-btn') { forgotPas ...

Curved edges, Layering, Content overflow restriction

My design consists of two circular divs with the border-radius property set to its max value. The first circle contains a header div with a unique background-color and overflow:hidden to create the illusion that the top portion of the circle has a differen ...

Encounter a Mongoose Error when Implementing Custom Schema

Take a look at my code below: var user_schema = new Schema({ name: String, last_name: { type: String, required: true, maxlength: [50, "username not valid "], }, password: { type: String, minlength: [8, "El password is short"] ...

Grabbing <object> HTML using jQuery

One example on my webpage is the presence of the following <object>: <object id="obj1" data="URL"></object> Could you please suggest a method to access this html object using jQuery? ...

Upgrade from using a switch statement to a more robust pattern in JavaScript

I am looking to enhance my app by dynamically displaying pages based on a user's type and role properties. Currently, I am using a simple switch statement that determines the view based on the user's type, like this: switch(type) { case ' ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

What is the technique for choosing the parent's ID with jQuery?

When a user clicks on any team, I need to retrieve the parent's parent ID. For example, if someone clicks on a Premier League Team, I want to store the ID 2 in a variable called league_id. Here are my attempts so far: Using Closest Method $('u ...

Only carry out a redirect to the specified page if the successRedirect is present in the passport.authenticate function

Encountering some difficulties with a Node Express app. After removing the successRedirect property in the auth method by passport, it fails to redirect. The below code does not redirect to the desired page when the successRedirect is removed and replaced ...

Methods for altering the color of a div using addEventListener

Why doesn't the color change when I click on the div with the class "round"? Also, how can I implement a color change onclick? var round = document.querySelector(".round"); round.addEventListener("click", function() { round.style.backgroundCol ...

What is preventing bots and crawlers from detecting Next.js meta tags?

I'm currently using Next.js with Typescript and MongoDB to retrieve data. I'm encountering difficulties in rendering the page because the crawler is unable to detect the meta tags. For instance, Bing Search Engine claims that Title and Meta desc ...

Develop a loading modal for all AJAX requests, with the exception of a specific one

I've implemented a code snippet to display a modal for ajax requests: $(document).ajaxStart(function () { showLoadingModal(); }); $(document).ajaxError(function () { closeLoadingModal(); alert("error"); }); Although this code creates a modal ...

Python Selenium encountering the StaleElementReferenceException bug

I'm encountering an issue with Selenium in Python that reads: selenium.common.exceptions.StaleElementReferenceException: Message: u'stale element reference: element is not attached to the page document\n Interestingly, this error occurs at ...

Arranging arrays of objects based on their occurrence rate

I am working with an array of objects that looks like this: students = [ { "name": "Ana Barbique", "category":"B" } { "name": "Marko Polo", "category":"B" } { "name": "Nick Harper", "cate ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

Extracting data from a Firebase realtime database JSON-export is a straightforward process that can be

I'm currently working with a Firebase realtime database export in JSON format that contains nested information that I need to extract. The JSON structure is as follows: { "users" : { "024w97mv8NftGFY8THfQIU6PhaJ3" : { & ...

Issue with Wordpress Submenu Items not Displaying

I've included sub menu items in my primary navigation, but they're not visible at all? I've examined the css and haven't found any code that would hide the sub menu. ul.art-hmenu { display: inline-block; vertical-align: midd ...

Duplicate key error in Node.js/Express with req.param

Whenever my node.js/express server encounters an error due to the failure of saving an object (through a post request), I noticed that the req.param key ends up being duplicated. Take, for instance, my node.js code: User.create({ username: req.param("use ...

Converting a variable with a cloned object from jQuery to vanilla JavaScript

const clonedBoardCode = $('#board_code').contents().clone(false); alert( clonedBoardCode.filter('div').eq(x).children().eq(y).text() );//need to fix this I am looking for a code similar to this $('#board_code_dup > div') ...

The Jade template engine encountered a problem when attempting to include the <p> tag within a div element

Encountered an issue when trying to add a "p" tag inside the div. Here is my code: !!! html head title= title link(rel='stylesheet', href='/stylesheets/#{stylesheet}.css') link(rel='stylesheet', href='/styles ...