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

Utilizing jQuery AJAX to efficiently handle branching based on the result received

I've successfully set up my first AJAX call with jQuery. The only thing left to do is to check the result from the PHP page for any database errors and display an error message if necessary. Here's the current Javascript code: <script type=" ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

Looking for a solution to a problem with your vertical CSS/jQuery dropdown menu

My web app features a vertical CSS menu that is working correctly except for one minor issue. When I mouse out on all elements with the class a.menutoggle, the last dropdown menu remains open. I am struggling to find a solution to hide it. Can someone plea ...

Using Flask and AngularJS: Managing Scope in a Controller with Flask Templating

Currently, my primary objective is to create a table with sortable columns. While following a tutorial and attempting to implement it into my project, I have encountered an issue. It seems that the structure of my code will not allow this functionality to ...

Updates to props values are not being reflected in the React js application running on the webpack

I keep facing an issue where I have to restart the webpack server every time I try to pass or update props values from parent to child components. It's frustrating that the props values are not updating even after saving the file. Take a look at my p ...

What is the best way to format my JSON data as a table on the screen?

I need to display my data in a table format at the bottom of the screen, as shown in the screenshot below. Here is an example of the top part code: This code snippet is also used for movies. <View> <Text key={item.symbol}>{item.symbol}<Te ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

Using Ruby variable as a parameter in JavaScript

Is there a way to include a ruby variable as a parameter in a JavaScript function for a Rails checkbox? Here is an example of what I'm trying to do: <%= check_box_tag 'Sugestão', prato.id , prato.sugestao,:class => prato.categoria_pr ...

Implement CSS to globally style material.angular's mat-card by customizing the background color

Looking for a way to globally change the background of mat-card on material.angular.io. I attempted adding the following code snippet to styles.css with no success. mat-card { background-color: purple; } ...

What is the best way to display index.ejs when the input field is blank?

If the input field is left empty when I click the form button, I want to redirect to "/". After clicking the button, the desired URL should be: http://localhost:3000 Header.ejs <form action="/search" method="GET"> < ...

What is the best way to pinpoint the origin of the element.style being injected by JavaScript?

I've been tasked with updating a client's WordPress website, but I'm still getting acquainted with the overall structure of the site. When looking at the blog page (), I noticed that posts are displayed within a wrapper labeled #blogleft, a ...

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

What is the best way to ensure that text highlighting appears consistent on all browsers?

I am facing an issue with the appearance of text highlighting between Chrome and Firefox browsers. Is there a way to ensure consistency in the appearance across all browsers? a { text-decoration: none; font-weight: 900; font-size: 4vw !impo ...

Styling the background of a container in CSS using Bootstrap

Currently, I am utilizing bootstrap and trying to find an elegant solution for adding a background to my container. Specifically, I am working with the bootstrap class container, as opposed to container-fluid. The official Bootstrap documentation advises ...

Can you explain the difference between synchronous and asynchronous loading?

After exploring this website, I have learned that when using CommonJS, the browser loads files one by one after downloading them, which can lead to dependencies slowing down the process. However, with AMD, multiple files can be loaded simultaneously, all ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

What is the best way to highlight titles that are unique but still prominent?

.test{ display:none; } .title:nth-child(odd){ background: #ddd; } <div class='title'>lorem</div> <div class='title'>lorem</div> <div class='title test'>lorem</div> <div class='tit ...