Implementing JavaScript functionality to read and interact with a Boolean field in a

Within my models.py file, I've defined the following:

urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje")

I am attempting to execute a javascript function that will modify a text field based on whether the Boolean field is set to 'True' or 'False'. However, I'm encountering an issue where I am unable to retrieve the value. Whenever I utilize

document.getElementById('id_urgency').value;
, it consistently returns 'on', regardless of whether the checkbox is checked or not. What could be causing this? Am I misinterpreting the value?

<script type="text/javascript">
     function makeReadOnly()
         {
          var a = document.getElementById('id_urgency').value;
          console.log(a);

          if (document.getElementById('id_urgency').value == 'True'){
              document.getElementById('id_date_days').readOnly = true;
         }else if (document.getElementById('id_urgency').value == 'False'){
              document.getElementById('id_date_days').readOnly = false;
          }
         }
     document.getElementById('id_urgency').addEventListener('change', makeReadOnly);

This code snippet is part of a Django form. Upon inspecting the page, I noticed that the Checkbox element does not have a value assigned to it. Why might this be the case?

input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"

Answer №1

When utilizing the .value method, you retrieve the value associated with a checkbox, not its checked state.

To determine if a checkbox is checked, you can use:

var a = document.getElementById('id_urgency')<b>.checked</b>;

Alternatively, as mentioned on javascripttutorial.net:

To verify if the accept checkbox is checked, utilize this code snippet:

const cb = document.getElementById('accept');
console.log(cb.checked);

(…)

Fetching the value attribute of a checkbox will always return the string 'on', regardless of whether the checkbox is checked or not. For instance:

const cb = document.getElementById('accept');
console.log(cb.value); // on

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

Guide on programmatically concealing a Bootstrap Offcanvas element using JavaScript and Blazor

In my Blazor .Net 8 web application, I have implemented a Bootstrap 5.3 Offcanvas component as a menu for selecting items. I wanted the Offcanvas to close automatically when a user selects an item from the menu. To achieve this functionality, I created a ...

Error: An uncaught exception occurred when trying to access a seekable HTML5 audio element, resulting in an IndexSize

While trying to utilize the HTML5 API along with SoundManager2, I encountered an issue. My goal was to determine the duration of a song in order to create a progress bar that would update as the song played. However, every time I attempted to retrieve the ...

Sending arrays' values in JavaScript

Here is a list of different groups to choose from: <select multiple="multiple" name="groups[]" id="groups[]" class="myclass"> <option value="1">Employees</option> <option value="2">Vendors</option> <option valu ...

Troubleshooting type casting issue in Typescript when working with objects containing getters and setters

I'm facing an issue with the code snippet provided. I suspect it might be related to casting, but I'm unable to pinpoint the exact solution. interface Code { code: string; expiration: number; } interface IActivationCode { [userId: string] ...

Can the combination of a JavaScript frontend and NodeJS backend function effectively together in this scenario?

I have a Domain-A that serves as a static site on Netlify, offering shopping cart functionalities. On the other hand, I have Domain-B hosting a backend server running a Node.JS payment system and utilizing Auth Services through passport.js. Due to its na ...

Retrieve attributes of an html element modified by AJAX request

I am currently developing a small project that involves performing CRUD operations on a MySQL table using PHP and jQuery. The table is integrated into the layout in the following manner: <?php require '../connect.php'; $sql = "SELECT id ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

Leveraging the TMDb API within the Django Web Framework to fetch movie posters stored in a database

Currently, I am working on a project to display all movies in the database as a list with their respective posters. However, I seem to have encountered an issue in my view class while attempting to make a request. Each movie in the database has a 'tmd ...

Insert a new store into an existing IndexedDB database that is already open

After opening and passing the onupgradeneeded event in IndexedDB, is there a way to create a new store? My attempted code: var store = db.createObjectStore('blah', {keyPath: "id", autoIncrement:true}); This resulted in the following error mess ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

No default export function available on this page

Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration. Let me showcase my code: import type { NextApiRequest, NextApiResponse } from 'next' import { connectMongoDB } fro ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...

Extracting data from JSON array

The output I am receiving is: [{"ref":"contact.html","score":0.7071067811865475}] $.getJSON( "index.json", function(data) { idx = lunr.Index.load(data); var searchResults = idx.search(variabletosearch); var formattedResults = JS ...

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...

What is the most effective way to assess if two JavaScript arrays contain the same values?

I am looking to specifically identify if the second array contains any values matching a value from the first array, rather than comparing the arrays as a whole. The goal is to return the value that matches in both arrays. To clarify, comparing two arrays ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...

Tips for displaying consecutive information from a Sequelize query with associations in Node.js

Attempting to create a straightforward sequential output from a demo Node.js app and Sequelize has proven to be challenging for me. I'm struggling to comprehend how promises and Bluebird can assist me in achieving the desired result: User: John Doe ...

Error receiving by React while updating an array with setState() in TypeScript

I am in search of a way to adjust a property of an item within an array by using the updater returned from setState. The function is passed down as props to the child, who then invokes it with their own index to update their status. const attemptToUpdate ...