JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue.

If you'd like to view the working version, here is the Fiddle demo.

Below is the snippet of code that isn't working:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
<script type="text/javascript">
$('#Checkbox1, #Checkbox2').on('change', function () {
    console.log();
    if ($('#Checkbox1').is(':checked') && $('#Checkbox2').is(':checked')) {
        $('#circle_2').css('background-color', '#999');
    } else {
        $('#circle_2').css('background-color', 'transparent');
    }
});
</script>

<style type="text/css">

#circle_2 {
    border:solid 1px #333;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display:inline-block;
}
#circle {
    border:solid 1px #333;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display:inline-block;
}
.circle_text{
    text-align:center;
    font-family:Arial, Helvetica, sans-serif;
    font-size:37px;
    color:#333;
    font-weight:bold;
    }
</style>


</head>

<body>
<div id="position_1">
                <div id="circle">
                    <p class="circle_text">

                        #1
                    </p>
                </div>
            </div>
            
            <div id="position_2">
                <div id="circle_2">
                    <p class="circle_text">

                        #2
                    </p>
                </div>
            </div>

            <br/><br/>

        <input type="checkbox" value="1" id="Checkbox1" name="Checkbox1"/> Answer one <br/>
        <input type="checkbox" value="1" id="Checkbox2" name="Checkbox2"/> Answer two <br/>
        <input type="checkbox" value="1" id="Checkbox3" name="a3"/> Answer three <br/>
        <input type="checkbox" value="1" id="Checkbox4" name="a4"/> Answer four <br/>
        <input type="checkbox" value="1" id="Checkbox5" name="a5"/> Answer five <br/>
        <input type="checkbox" value="1" id="Checkbox6" name="a6"/> Answer six <br/>
        <input type="checkbox" value="1" id="Checkbox7" name="a7"/> Answer seven <br/>
        <input type="checkbox" value="1" id="Checkbox8" name="a8"/> Answer eight<br/>
        <input type="checkbox" value="1" id="Checkbox9" name="a9"/> Answer nine <br/>
        <input type="checkbox" value="1" id="Checkbox10" name="a10"/> Answer ten <br/>

</body>
</html>

I have a feeling I may be overlooking something crucial for proper loading, but I haven't been able to identify it yet.

Answer №1

Make sure to enclose your jQuery code within a document ready function.

$(document).ready(function () {
    $('#Checkbox1, #Checkbox2').on('change', function () {
        console.log();
        if ($('#Checkbox1').is(':checked') && $('#Checkbox2').is(':checked')) {
            $('#circle_2').css('background-color', '#999');
        } else {
            $('#circle_2').css('background-color', 'transparent');
        }
    });
});

You can also place it before the closing body tag. Running the code before the elements are loaded will cause issues. When using jsFiddle.net, the document ready call is automatically added around your code.

Answer №2

When the document is ready, JSFiddle will automatically execute the code. However, if you want to run it in your local file, make sure to include it yourself.

To update your JavaScript, use this snippet:

$(document).ready(function() {
    $('#Checkbox1, #Checkbox2').on('change', function () {
            console.log();
        if ($('#Checkbox1').is(':checked') && $('#Checkbox2').is(':checked')) {
            $('#circle_2').css('background-color', '#999');
        } else {
            $('#circle_2').css('background-color', 'transparent');
        }
    });
});

Answer №3

Ensure your code runs after the <head> section has loaded to avoid issues with missing checkboxes. Use $(document).ready() to wait for the page to finish loading, or place your code after the relevant elements within the <body>.

<script type="text/javascript">
$(document).ready(function(){
    $('#Checkbox1, #Checkbox2').on('change', function () {
        console.log();
        if ($('#Checkbox1').is(':checked') && $('#Checkbox2').is(':checked')) {
            $('#circle_2').css('background-color', '#999');
        } else {
            $('#circle_2').css('background-color', 'transparent');
        }
    });
});
</script>

If using JSFiddle, consider utilizing the default option in the left sidebar to execute the code in an onLoad handler. This should help resolve any similar issues experienced on that platform.

Answer №4

Embed the jQuery code within a document ready function:

$( document ).ready(function() {
  $('#Checkbox1, #Checkbox2').on('change', function () {
    console.log();
    if ($('#Checkbox1').is(':checked') && $('#Checkbox2').is(':checked')) {
        $('#circle_2').css('background-color', '#999');
    } else {
        $('#circle_2').css('background-color', 'transparent');
    }
});
});

Ensure that you are connected to the internet as the jQuery library is loaded dynamically from the server at runtime. Without an internet connection, your code will not function properly.

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

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

Dividing an array in PHP using Ajax

Hey there, I have successfully sent data from PHP to Ajax using Json but now I need help in splitting the response. Can anyone guide me on how to alert each element separately? $.ajax({ url:"myHandler.php", type:"POST", ...

Utilizing Z-index for the arrangement of DIVs and elements in a webpage

I am facing an issue with my website design where the content section overlaps with the banner. This causes the content section to be hidden behind the banner, and I need it brought to the front. The problem specifically lies with the search element on my ...

An effective way to connect the ng-model of a <select> element with ng-options within an ng-repeat loop

My task list consists of: [{ Title: "Title1", Position: "9" },{ Title: "Title2", Position: "1" },{ Title: "Title3", Position: "5" },{ Title: "Title4", Position: "7" }] I am attempting to generate a series of <select> ...

What is the best way to add shadow effects to a DIV using CSS?

Is there a way to add shadows within an element using CSS? I attempted the following method but it did not work: #element { shadow: 10px black; } ...

The styling of MUI components adapts when the Navigate component in React Router is initialized

Incorporating React Router into my application has led to an unexpected side-effect while implementing the <Navigate to="/"> component (which goes to <AthleteHomepage />) upon state change. Currently, I haven't set up dynamic sta ...

A nifty little JavaScript tool

Recently, I created a bookmarklet that opens a new window with a specified URL and passes variables to a PHP script using the GET method. However, I now require it to load the same PHP script and pass the same variables but within a div element this time. ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

Waveform rendering in HTML5 using wavesurfer.js struggles to handle large mp3 files

Recently, I was considering incorporating wavesurfer.js into one of my projects so I decided to explore the demo on To test it out, I uploaded a large mp3 file (approximately 2 hours long) onto the designated area in the middle of the page. It appeared to ...

"XMLHttpRequest 206 Partial Content: Understanding the Importance of Partial

I need help with making a partial content request using an XMLHttpRequest object in JavaScript. Currently, I am trying to load a large binary file from the server and want to stream it similar to how HTML5 video is handled. While setting the Range header ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Removing files from a selection during a multi-file upload process in PHP

How can I remove file content from selected files during multiple file uploads and update the form after removing the file to send data to another PHP page using AJAX call function? I am inexperienced in handling multiple files. ...

Decrease the heaviness of a Glyphicon

How can I make Glyphicons appear lighter in weight? I have utilized the "ok" Glyphicon <span class="glyphicon glyphicon-ok"></span> which currently displays as follows: Is there a method to decrease the weight of the icon in order to create a ...

Implement a grid layout for columns within the profile section

Each user on my website has a profile tab that displays their submitted posts. To showcase these posts, I utilize the following code: <?php while ($ultimatemember->shortcodes->loop->have_posts()) { $ultimatemember->shortcodes->loop-> ...

Learn how to easily modify a value in a CVS file by simply clicking on the data point on a highcharts graph

Is there a way to update my CSV file by clicking on a graph? I want to be able to create a graph from data in the same CSV file and then, when I click on a point, set that point to zero on the y-axis and update the corresponding value in the CSV file to 0. ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Utilizing values from .properties files in Java with Spring for internationalization: A straightforward approach to handle Strings

Here is the code snippet I am using: @Value("${app.user.root}") private String userRoot; This code helps me to fetch a constant value from my application.properties file. Within my GetMapping method, I need to redirect to the error page and pass a S ...