Is it possible to showcase dates within input text boxes prior to POSTing the form?

I am currently working on a form that posts to a PHP script by selecting a date range. For a better understanding, you can check out my visual representation here. Before the data is posted, I would like to display the selected dates in empty boxes or input fields based on the radio button chosen. Can anyone help me with this issue?

Thank you in advance!

Here is an example of what I am trying to achieve:

 When I select one month ago:
(  )       (  )     (X)     (  )
1 day    1 week    1 month    3 months

-----------------
|2014 - 11 - 01  |   Date From: (the selected date)
-----------------

-----------------
|2014 - 12 - 01  |  Date To: (current date)

---------
| Get AHT |  (button)
--------- 

Below is the structure of my form:

<div id="menu_option">
        <h1>Menu Option</h1>
            <div id="button_position">


        <div id="date_selector">    
            <label>Select Date Range</label>
            <form action="show_aht2.php" method="post" id="formtopost">
                    <input type="radio" name="date_selected" value="1d" checked="checked"/>1d
                    <input type="radio" name="date_selected" value="1w" />1w
                    <input type="radio" name="date_selected" value="1m" />1m
                    <input type="radio" name="date_selected" value="3m" />3m
                    <input type="button" id="aht_btn" name="get_aht" value="Get AHT" />
            </form>
  </div><!--date selector-->

                <div class="clear"></div>   

  <button id="refresh_page">Refresh Page</button>

    </div>

CSS: I need assistance in displaying the date boxes before the AHT button and also making all buttons the same size.

/*container for all divs inside*/
#container {
width:1450px;   
}

/*map size*/
#map_size{
width:1190px;
height:1300px;
background:#0099FF;
border-style: solid;
border-color: black;
position: relative;
float:left;
}

/*menu bar option*/
#menu_option{
width:230px;
height:600px;
background:#0099FF;
border-style: solid;
border-color: black;
position: relative;
float:right;
overflow:hidden;
text-align:center;
}

input[type="radio"] {
margin-left:10px;
}

#date_selector{
border:3px;
border-color:black;
}

#button_position{
/*width: 100px;
height: 80px
position: absolute;*/
}

#button_position button{
font-weigth:bold;    
font-size:1.3em;
}

button:hover{
cursor: pointer;
}

button {
margin:5px auto; 
font:16px tahoma; /*every size you want.*/
}

/*clear */
.clear {
clear:both;
}

Answer №1

If you're looking to display a live date range before submitting the form and want the dates to be included in the submission, you can achieve this by incorporating two readonly text boxes in your form along with the following JavaScript code.

HTML

<input type="text" id="from_date" name="from_date" readonly="readonly" />
<input type="text" id="to_date" name="to_date" readonly="readonly" />

Javascript

<script type="text/javascript">
    function formatDate(d) {
      var dd = d.getDate()
      if ( dd < 10 ) dd = '0' + dd;

      var mm = d.getMonth()+1
      if ( mm < 10 ) mm = '0' + mm;

      var yy = d.getFullYear();
      if ( yy < 10 ) yy = '0' + yy;

      return yy+'-'+mm+'-'+dd;
    }

    function getDateRange(value){
        var now = new Date(),
            y = now.getFullYear(),
            m = now.getMonth(),
            d = now.getDay();

        var diff = {};
        diff['1d'] = 1;
        diff['1w'] = 7;
        diff['1m'] = 30;
        diff['3m'] = 90;
        var from_date = new Date(y, m, d - diff[value]);

        $('#from_date').val(formatDate(from_date));
        $('#to_date').val(formatDate(now));
    }

    $(function(){
        $("input[name=date_selected]").click(function(){
            getDateRange($(this).val());       
        });
        getDateRange($("input[name=date_selected]:checked").val());
    });
</script>

Check out the working code on JSFiddle.

Answer №2

<form method="post" id="formtopost">
    <input type="radio" name="date_selected" value="1" checked="checked"/>1d
    <input type="radio" name="date_selected" value="7" />1w
    <input type="radio" name="date_selected" value="30" />1m
    <input type="radio" name="date_selected" value="90" />3m
    <input type="button" id="aht_btn" name="get_aht" value="Get AHT" />
    <input type="submit" />
</form>
<?php
    if($_POST && $_POST['date_selected']){
        $today = new datetime();
        $date_selected = new datetime('-'.$_POST['date_selected'].' days');

        echo '-----------------<br />';
        echo '| '.$today->format('Y-m-d').' |<br />';
        echo '-----------------<br />';
        echo '| '.$date_selected->format('Y-m-d').' |';
        echo '-----------------<br />';

    }
?>

Answer №3

To accomplish this, a common method is to utilize JavaScript to update the input elements' values when the radio button value changes. In order to prevent any alterations in the input boxes, you can assign them the attribute disabled="disabled".

<script type="text/javascript">
function setDate(newVal) {
    document.getElementById('dateInput').value = newVal;
</script>

<input type="radio" name="selectedDate" value="1d" onchange="setDate('1 day')" checked="checked"/>
<input type="radio" name="selectedDate" value="1w" onchange="setDate('1 week')"/>
<input type="radio" name="selectedDate" value="1m" onchange="setDate('1 month')"/>
<input type="radio" name="selectedDate" value="3m" onchange="setDate('3 months')"/>

<input type="text" name="dateInput" id="dateInput" value="1 day" disabled="disabled">

Answer №4

Here is the solution you've been searching for: http://jsfiddle.net/jpkp0o0w/2/

    $("#aht_btn").click(function () {
    var someDate = new Date();


var someFormattedDate = dd + '/'+ mm + '/'+ y;
    var valSelected = $("[name=date_selected]:checked").val();
    if(valSelected == "1d")
    {
       someDate.setDate(someDate.getDate() - 1); 
    }

    if(valSelected == "1w")
    {
        someDate.setMonth( someDate.getDate() - 7);

    }

    if(valSelected == "1m")
    {
        someDate.setMonth( someDate.getMonth() - 1 );

    }

    if(valSelected == "3m")
    {
        someDate.setMonth( someDate.getMonth() - 3 );

    }

    var dd = someDate.getDate();
    var mm = someDate.getMonth() + 1;
    var y = someDate.getFullYear();
    $("#datefrom").text(y + "-" + mm + "-" + dd);
});

UPDATE

To make it work differently, just modify the event : http://jsfiddle.net/jpkp0o0w/7/

$("[name=date_selected]").click(function () {

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

EJS file not displaying stylesheets and images correctly during rendering

I'm currently in the process of building a website, but when I try to render an ejs file (index.ejs), only the HTML portion is displayed without showing any stylesheets, fonts, or images. Here is the code snippet for linking the stylesheets: <!D ...

In Python 2.7, we can utilize scraping techniques along with the 're' library to extract float numbers from a given string. By using the '

I just scraped this content import re import urllib from BeautifulSoup import BeautifulSoup After scraping, I have results like this (printed numbers_in_mill.text): 9.27[7] 9.25[8] 10.17[9] 10.72[10] How can I modify these results to get: 9. ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Guide to building a seamless page without refreshes with the help of jquery, express, and handlebars

I need assistance with my express JS project. I am trying to set up two pages using NodeJS, incorporating handlebars as the template engine. My objective is to have the first page rendered using res.render('home'), and for the second page to be l ...

Check to see if modifying the HTML using jQuery results in any errors

Although it may sound straightforward, let me clarify. I am utilizing ajax calls to update the content of the body and I aim to trigger an alert if the updating process fails on the client side, specifically after receiving a response from ajax in case of ...

Unable to display images in the ngImgCrop upload preview modal screen

Currently, I am utilizing ngImgCrop to enable an upload preview and square crop feature for profile pictures. Unfortunately, I am experiencing issues where neither the image preview nor the cropping functionality are being displayed. 'use strict ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Activate the clicked tab in the Bootstrap navbar when selected

I have gone through similar posts, but I am unable to get mine to work. My goal is to activate the clicked tab. Here is what my bootstrap navbar looks like in HTML: <div class="navbar navbar-default" role="navigation"> <div class="container" ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Converting an HTML table into a visual image

I've encountered an issue. My task involves transferring an HTML table to a PDF using fpdf. Is there a way to transform an HTML table into an image (via URL link)? ...

Unusual behavior observed when filling a Spinner from a database source

I am facing an issue while trying to populate a spinner from a MySQL database using JSON. The data is successfully exported, but the app crashes when I click on the Spinner to show the dropdown menu. The JSON output from the database can be viewed here. ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

What is the trick to getting the <label> and <input> elements to show up side by side in an HTML form?

I am designing a registration form for a new website. My goal is to have each label and its corresponding input element displayed on the same line. Here's the CSS code I'm using: #registration-form { background-color: #FFF; height: 600px; ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

"Hello there, let's chat about the need for require

I have been trying to organize my files by separating them and not putting everything in the function.php file. Here is what I have done: function required_theme_files() { require_once( get_template_directory() . '/inc/customize/color.php' ); ...

Retrieve the data within a div element until a specified location

Using the PHP Simple HTML DOM Parser, I am extracting all paragraph tags by executing this code: // Product Description $html = file_get_html('http://domain.local/index.html'); $contents = strip_tags($html->find('div[class=product-detail ...