What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files.

Below is a snippet of the JavaScript file:

function getSelectedText() {
        if document.getElementById("card1").checked == true {
            //code here
        }
}

And here is the HTML it's attempting to access:

<script type="text/javascript" src="js/cards.js"></script>
<input id="card1" type="radio" name="card" value="1" checked>Test1<br>
<input id="card2" type="radio" name="card" value="2">Test2<br>
<input id="card3" type="radio" name="card" value="3">Test3<br>
<button onclick="updateCard()">View card</button>

I'm struggling to manipulate the radio inputs as the JavaScript file throws an error when referencing the document. Is there a way to achieve this without embedding the code directly into the HTML or should I consider an alternative method?

Answer №1

Initially, make sure it reads:

if (document.getElementById("card1").checked)

Don't forget to include the pair of brackets. To ensure the JavaScript code functions properly, be sure to add a

<script src="your js file"></script>
element in your HTML file, and everything should work smoothly.

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

The Ajax Auto Complete function encounters an issue when attempting to assign a value to the TextBox

I have a Textbox that utilizes an Ajax Autocomplete function. The function is functioning correctly and retrieves values from the database, populating them in the TextBox as well. However, there is a button on the page that triggers a query, fetching som ...

Exploring the Form's data-url Attribute

My form tag is set up like this: <form data-id="213" method="post" onsubmit="javascript: startAjax(); return false;"> <input type="submit" value="submit"> </form> When I submit the form, an ajax script runs to validate some information ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

The $_REQUEST variable is functioning properly, while the $_POST variable seems to

I currently have an HTML form using the post method. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript& ...

Interactive search tool for toggling visibility of elements

Hello everyone, this is my initial post on StackOverflow. Keeping my fingers crossed that it goes smoothly! <input type="Text" id="filterTextBox" placeholder="Filter by name"/> <script type="text/javascript" src="/resources/events.js"></scr ...

Utilizing the Invision prototype for embedding

They provided me with this code snippet <iframe width="424" height="916" src="//invis.io/U5574OIA3" frameborder="0" allowfullscreen></iframe> However, I am unsure of how to properly embed it. I attempted to insert the line into my website but ...

There appears to be an issue with the functionality of the Bootstrap toggle tab

Currently, I am facing a toggle issue and having trouble pinpointing the root cause as there are no errors appearing in the console. The problem involves two tabs that can be toggled between - "pay" and "method". Initially, the default tab displayed is "pa ...

Sending emails through a basic HTML/PHP form is incredibly time-consuming

Seeking assistance with optimizing my email form that utilizes the POST function alongside a PHP mailto() feature. The process of sending the form takes significantly longer than expected. Any suggestions or guidance would be greatly appreciated. Here&apo ...

The footer at the bottom of the page is currently malfunctioning

I was able to create an always on the bottom footer using code from Codepen. Here is the HTML: <div class="content"> <header> <p>blabla</p> </header> <main> <p>blaBlabla blub</p ...

What causes delayed state updates in React/NextJS until another state is updated or a fast refresh occurs?

UPDATE: Version 13.3.0 is coming soon! In my code, I have a state variable named localArray that I need to update at a specific index. To achieve this, I decided to create a temporary array to make modifications and then set the state with the updated val ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

The results of the jQuery selector appear differently in the browser console compared to PhantomJS

What could be causing the discrepancy in results when using the same jQuery selector? Visit this website for reference: See below code involving node.js and phantomjs-node(bridge): phantom.create(function(ph){ ph.createPage(function(page){ p ...

Navigating around potential type errors when passing data for chart.js can be challenging. Here are some strategies to

I'm currently working on an application that includes a chart, and I'm facing an issue while trying to populate the chart with data from my store. The error occurs when I attempt to pass the chartData object through props to the data property of ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component: <template> <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component {{menu.title}} <li> </template> <script> ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Align text to the right and do not include any images

I am attempting to align the images back to the left under the title, while only floating the description text to the right. I am struggling with clearing the image floats. HTML: <div class="title">System Displays</div> <div class="descrip ...