Techniques for retrieving user inputs upon loading the HTML document and detecting changes using JavaScript

I am new to using JS to pass data to Python. I have managed to collect the values when the HTML is loaded, but I am facing an issue where the value does not change when it is updated.

Here is the code snippet that I have been working with:

<input type="date" id="start-date" name="start-date" value="2019-10-10"/>
<label for="date">to</label>
<input type="date" id="end-date" name="end-date" value="2020-05-10"/>

<script>
  document.onreadystatechange = function () {
    var start_date = document.getElementById("start-date").value;
    var end_date = document.getElementById("end-date").value;

    $.ajax({
      url: "/dates",
      type: "GET",
      data: {
        start_date: start_date,
        end_date: end_date,
      },
    });
  };
</script>

Answer №1

document.onreadystatechange doesn't really have a purpose.

You should be using a change event instead

In this approach, I am delegating from the document.

window.addEventListener("DOMContentLoaded", function() { // only necessary if the script is not placed after the date elements
  document.addEventListener("change",function(e) { // this can be more specific to a closer container like a form
    const tgt = e.target;
    if (!tgt.matches("[type=date]")) return; // if it's not a date change
    let start_date = document.getElementById("start-date").value;
    let end_date = document.getElementById("end-date").value;
    $.get("/dates", {start_date, end_date },function(data) {
      console.log(data); // data returned from server
    });
  });
}); 

An alternative method using the same event handler for both dates

window.addEventListener("DOMContentLoaded", function() { // only needed if the script is not placed after the date elements
  const startDateField = document.getElementById("start-date");
  const endDateField = document.getElementById("end-date");
  const dateChange = e => { 
    let start_date = startDateField.value;
    let end_date = endDateField.value;
    $.get("/dates", {start_date, end_date },function(data) {
      console.log(data); // data returned from server
    });
  };
  startDateField.addEventListener("change",dateChange);
  endDateField.addEventListener("change",dateChange);
}); 

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

Create a unique functionality by assigning multiple event handlers to a single event

I am looking to add a JavaScript function to an event that already has a handler function. The new function should complement the existing one rather than replace it. For instance: There is a function named exFunction() that is currently linked to docume ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Setting maximum and minimum zoom limits for an element ID using JavaScript or jQuery

My application features a DIV element with the unique identifier of mainDiv. The issue I am facing is related to zooming functionality, as it currently lacks any set limits - both for scaling up and scaling down. I have been searching on Google for a sol ...

The issue of flickering during the combination of slideToggle and animate in jQuery

I want to incorporate a hidden div that, when triggered by a button click, will smoothly reveal itself and "push" away part of another div without changing the overall size of the containing div. However, I have encountered an issue where the div below th ...

Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks: Check if a given array can represent Preorder Traversal of Binary Search Tree This is the algorithm they provided: 1) Cr ...

Minimization tools for compressing CSS and JavaScript documents

After deploying my application, I noticed that the loading time has significantly increased. Is there a way to compress CSS and JS files? I include only the necessary code in each page and occasionally use minified versions of JS. Thank you. ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Issues with jQuery .submit() function not functioning properly following an ajax request

I am having an issue where I want to automatically submit a form if a certain condition is true, but for some reason it's not working as expected. I have tried debugging with firebug, but the form isn't getting submitted and I can't figure o ...

Analyzing various PHP $_POST keywords for validation

Currently, I am facing an issue with a page where a script is supposed to check if the POST request contains a certain keyword when a link is called. However, no matter how I arrange the code, it does not seem to work as expected. <?PHP if($_POST[&apo ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

"Retrieve the values of the items that have been chosen from a list using jQuery

In my PHP page, I have a list displayed using the following script: <div id='demo' style="padding-left:20px"> <select name='lists[]' multiple='multiple' class='multiselect' > <?php $sql="select list ...

Update the board with a feature for uploading files

<asp:FileUpload runat="server" ID="uploadCertification" /> <asp:Button runat="server" ID="btntext" OnClick="btntext_Click" /> Snippet of Code uploadCertification.PostedFile.SaveAs(serverPathImage + "\\CertificationCompany\&bsol ...

What should we name this particular style of navigation tab menu?

What is the name of this tab menu that includes options for next and previous buttons? Additionally, is there a material-ui component available for it? ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

A different approach to joining strings

Is there a different method to combine a '#' symbol like in the code snippet below? radioButtonID = '#' + radioButtonID; ...

Unusual actions observed in ajax rails form calculator with pre-filled values

I have a form calculator in Rails that utilizes AJAX without a database. While it functions properly, I have noticed some peculiar behavior which I would like to address. Firstly, I navigate to the /interest_calculator page Then, I input 10 into @first_0 ...