Guide on retrieving the value property of an element with querySelector

I am new to JavaScript and have been working on some practice projects to improve my skills.

What is the best way to retrieve the value property of an element using its ID?

I have tried the following code, which seems to be working:

var billAmount = document.getElementById("billamt").value;

However, I would like to use the querySelector method instead of getElementById. What is the correct way to do this?

So far, the code I have tried has not worked:

var billAmount = document.querySelector("#billamt").value;

const billamt = document.querySelector('#billamt').value;

function calculate() {
  console.log(billamt * 0.25);
}
<label>How much did you pay?
  <input id="billamt" type="text" placeholder="Bill Amount">
</label>
<button onclick="calculate()">Calculate</button>

You can view the entire source code of the project by clicking on this link: https://codepen.io/anthony-bahinting/pen/dybegMW

Answer №1

Your code is attempting to evaluate the value of #billamt right away, even though there is no user input yet. It would be more efficient to first save a reference to the element and then request its value when the calculate() function is executed.

const billamtElem = document.querySelector('#billamt'); // Reference to HTMLElement

function calculate() {
  console.log(billamtElem.value * 0.25);
}
<label>How much did you pay?
  <input id="billamt" type="text" placeholder="Bill Amount">
<label>
<button onclick="calculate()">Calculate</button>

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

Is there a reason why this jquery is not functioning properly in Internet Explorer 8?

Seeking assistance to troubleshoot why this jQuery code is not functioning properly in IE8. It performs well in Chrome but encounters issues in IE. $(document).ready (function() { $('.first-p').hide(); $( "div.first" ).click(function() ...

The Google Maps directions stay visible even when new routes are generated

Utilizing the Google Maps Javascript API V3 in my Android WebView has presented a new issue. When I request directions from point A to B, it displays correctly. However, when I switch the endpoints to go from A to C, the route from A to B does not disappea ...

Unable to display an image element in fullscreen within a modal that is already fullscreen

I am facing an issue with my modal that is designed to occupy the full width and height of a browser. Inside this modal, there is an image enclosed within a div along with some other elements. My goal is to make the image go full screen in the browser, aki ...

Using ThreeJS/WebGL to Send Functions to Shaders

I have created a custom noise function that accepts a 3D coordinate (x, y, z) and returns a noise value between 0 and 1. I am interested in incorporating this function into my vertex shader to animate vertex positions. Can I access this external function f ...

error message remains visible even after correct input is entered

I am new to React and attempting to create a multi-step form using Reactjs and Material-ui. The form validation and submit buttons are working perfectly fine. However, I have encountered an issue with the code where if a field is empty and I try to proceed ...

Removing a Firestore Document when the identifier is assigned to a unique name that is not predefined in any location

Presently, my database stores user information. The unique identifier for each document is the user's initial name upon registration, even though this name may have been changed at a later time without updating the document's name. My dilemma is ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

Issue with getStaticProps functionality on Vercel seems to be persisting

UPDATE: I realize now that my mistake was calling my own API instead of querying the MongoDB database directly in getStaticProps(). I have made the necessary changes: export async function getStaticProps() { await dbConnect(); const user = await User.find ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

Experiencing trouble with retrieving the selected image source and showing it in a text field

Looking for help with a javascript issue related to image selection. My goal is to store the selected image's src in a variable and display just the folder ID and image ID without the path and file extension. I want this process to happen in real time ...

Performing an axios request using form data in a React JS application

I am trying to figure out how to use axios in react js to make a cURL request that is currently working. Here is the cURL request: curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id='uidxxxx'" --form "sign_id=" Every time I try to ...

The feature for adding a function in Moment.js seems to be malfunctioning

Unfortunately, the moment().add() function is not functioning properly in my JavaScript code. var theDate = moment(event.start.format("YYYY-MM-DD HH:mm")); //start Date of event var checkquarter = theDate.add(30, 'minutes'); var plus = 30; if ...

What could be causing the error message 'Uncaught SyntaxError: Identifier 'randFilmIndex' has already been declared'?

function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); } function arrayRemove(arr, value) { return arr.filter(function(ele){ return ele != valu ...

PHP Proxy - Sending Files using cURL

I am in the process of developing an application using AngularJS for the frontend and a Laravel-based API for the backend. To maintain security, I pass data through a PHP proxy before reaching the API. When it comes to POST requests, the proxy decodes the ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Preventing Click Events during Data Fetching in React.js without Using jQuery

In the redux store, there is a state called isFetching. When data is being fetched from the backend, this state becomes true. I need to disable all click events when isFetching is true, without using jQuery. I stumbled upon some solutions (involving jQuer ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

Tips for preventing the appearance of two horizontal scroll bars on Firefox

Greetings, I am having an issue with double horizontal scroll bars appearing in Firefox but not in Internet Explorer. When the content exceeds a certain limit, these scroll bars show up. Can someone please advise me on how to resolve this problem? Is ther ...

NodeJS Streams: Delay in data transfer with Readable.pipe()

My understanding was that Stream.Readable.pipe() would immediately pipe data as it receives it, but I'm facing unexpected results while trying to create my own streams. const { Writable, Readable } = require("stream"); const writable = new ...