I have already added the ID, yet I am unable to set the property 'onclick' of null

I've encountered an issue even after adding an id in HTML for JS. Upon opening the website, I see the following error:

Uncaught TypeError: Cannot set property 'onclick' of null

Your assistance is greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script>
var btn = document.getElementById("btn");
btn.onclick = function() {
    var arrays = new Array();
    var items = document.getElementsByName("check");
    for(var i=0;i<items.length;i++) {
        if(items[i].checked) {
            arrays.push(items[i].value);`enter code here`
        }
    }
    alert("numbers checked:" + arrays.length);
}
</script>
</head>
<body>
<input type="checkbox" value="1" name="check" checked/>
<input type="checkbox" value="2" name="check"/>
<input type="checkbox" value="3" name="check" checked/>
<input type="button" value="numbers you have checked" id="btn"/>
</body>
</html>

Answer №1

Give this a shot!

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8>
    <title>Add your title here</title>
</head>

<body>
    <input type="checkbox" value="1" name="check" checked/>
    <input type="checkbox" value="2" name="check"/>
    <input type="checkbox" value="3" name="check" checked/>
    <input type="button" value="selected numbers" id="btn"/>

    <script src="jquery-1.7.2.js" type="text/javascript"></script>;
    <script>
        var btn = document.getElementById("btn");
        btn.onclick = function () {
            var selectedNumbers = new Array();
            var items = document.getElementsByName("check");
            for (var i = 0; i < items.length; i++) {
                if (items[i].checked) {
                    selectedNumbers.push(items[i].value);
                }
            }
            alert("numbers selected:" + selectedNumbers.length);
        }
    </script>
</body>;

</html>

Answer №2

Replace the input with a button and execute the function in this manner:

<button id="btn" onclick="myFunction()">

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

Unable to save canvas as an image due to tainted canvas in a React application

I encountered an error after the line containing canvas.toDataURL(). An error message stating "Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvas may not be exported" was displayed. Despite attempting to search for ...

Error in Node.js: attempting to invoke the 'use' method on an undefined object

Currently in the process of learning about node.js and encountering a perplexing error. app.use(morgan('dev')); //log request to console TypeError: Cannot call method 'use' of undefined at Object.<anonymous> (/root/authproject/se ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

What is the process for transforming data objects into arrays of objects?

Currently, I am faced with a situation where I have one array containing 6 category names and 6 arrays of objects, each containing 5 objects related to those categories. I am seeking the most efficient way to restructure these data sets so that I end up wi ...

Trouble with Date.parse() function in JavaScript on Mozilla Firefox browser

I'm encountering an issue with parsing the dateTime value "01-01-2013 12:00:00 AM" in Mozilla Firefox. I have successfully parsed it using Date.parse("01-01-2013 12:00:00 AM") in Google Chrome and IE browsers, but Firefox seems to be giving me trouble ...

Error encountered: jquery form validation fails to register changes

I am currently developing a calculator-like code where users will submit a form multiple times, and I need to save the result of calculations only if there are changes in the form. For instance, when a user clicks the "Calculate" button for the first time, ...

Exploring the PayPal Checkout JavaScript SDK's CreateOrder call and interpreting the response

I am currently exploring how to use the JavaScript SDK to display PayPal payment buttons on a website. I am new to working with JSON and REST API calls, so I am facing some challenges in implementing this. The createOrder function is running smoothly and ...

I'm having trouble with my Associations not being detected and it's leading to a SequelizeEagerLoadingError. What

I'm currently working on designing the structure of my models in such a way that there is an association from the party table to both the Attendee and Item tables. This will allow me to query both tables using the Party_Id. However, it seems like I m ...

A step-by-step guide to implementing Google Analytics Event tracking using PHP

Implementing Google Analytics Events in Javascript can be done using the following code: ga('send', 'event', 'test', 'test','value'); I am trying to incorporate this feature throughout my entire project. ...

The content on my website is shown as &#039; instead of '

My PHP script returns a JSON object, and I have a JavaScript function that parses this JSON. I used htmlspecialchars in my PHP code, but when I display the values on my webpage &#039; is not being replaced by '. The same issue occurs with &quo ...

Is there a method within the jQuery Form plugin to display a new page upon successful completion of an Ajax request?

After a user uploads a photo, it goes through a controller (profile/upload_picture) for validation of file type and size. If there are validation errors, they will be displayed using Ajax on the frontend. This functionality is working smoothly. However, ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Persistent Error from Express Custom Validator

In my login API, there is a function called ifIDAlreadyExist that checks the database to validate new user details. It returns true or false depending on whether the ID exists or not. However, even when the result is false, an error message is still retur ...

Angular 6 data modification update: What you need to know

Whenever a new response is added to the array of 15 responses, I aim to dynamically update the view without requiring the page to refresh. addResponseToItemArray(res: DashboardInfo[]): void { this.item.push([]); // ERROR this.item.push([]); ...

Issues with AJAX functionality not operating properly in a web form, leading to automatic redirection to a PHP script. Possible solutions and troubleshooting

I have a feature on my web application that allows users to add their skills by clicking the "Add a Skill" button. It was working fine until I tried to incorporate something new. The issue is that when I click the "Add a Skill" button, it acts as though it ...

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Save pictures in an array and showcase them in an angular interface

I'm currently working on a project to create a user-uploaded image gallery, but I've run into an issue. Although I've been able to store the uploaded images in an array, I'm struggling to display them in the view. Below is the code sni ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Whenever I try to load an image from MongoDB, I encounter the error message: "data:image/png;base64,[object Object]."

I am currently facing an issue with displaying images in an HTML table that pulls data from MongoDB. The image is not showing up, and I'm struggling to identify the root cause of the problem. Here are the steps I have taken so far: Below is the Java ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...