setting the value of a form field to empty if another field is filled

After searching extensively, I couldn't find a solution to my specific issue. In my form, I have a field for a date and another one for the number of hours. What I need is a Javascript function that, when clicked, will check if the date field is empty and if so, automatically clear out the value in the adjacent text box.

This is how part of my form code appears:

<td>Day One:</td>
    <td width="250"><input type="date" name="dayone" onClick="document.getElementsByName('hours1')[0].value=8;" /></td>
    <td>Hours: (max 8) <input type="text" name="hours1" id="hours1" class="smalltext" ></td>

The onclick event currently fills the adjacent text field with '8' as a default value. I require assistance in implementing a feature that will revert this value to blank if the user removes the date from the other field.

Your help is greatly appreciated!

Answer №1

It's important to maintain clean HTML and utilize event listeners - check out the DEMO

HTML

<td width="250">
    <input type=date name="dayone" />
</td>
<td>
    Hours: (max 8)
    <input type="text" name="hours1" id="hours1" class="smalltext" />
</td>

JS

document.getElementsByName('dayone')[0].addEventListener("click", function() {
    document.getElementsByName('hours1')[0].value = 8;
}, false);

document.getElementsByName('hours1')[0].addEventListener("keyup", function() {
    if ( this.value == '' ) {
        document.getElementsByName('dayone')[0].value = '';
    }
}, false);

Answer №2

Give this a shot

<script>
   function resetForm(){
      var element = document.getElementById('hoursInput');
     element.value = '';
}
</script>

Check out the live demo here

Answer №3

Make a modification to your code by including an onblur event listener.

   <td width="250"> <input type=date name="dayone" onblur="checkValue" onClick="document.getElementsByName('hours1')[0].value=8;" /></td>

Additionally, create the following event handler:

function checkValue()
{
    var dayValue = document.getElementByName('dayone')[0].value;
    if(dayValue != '')
    {
       document.getElementByName('hours1')[0].value = '';    
    }
}

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

Preventing request interceptors from altering the request header value in Node.js

I am currently using the http-proxy-middleware to set up a proxy, and it is working smoothly. However, before I apply app.use('/', proxy_options);, I am attempting to intercept my request and update the request header. Unfortunately, the changes ...

Are there any possible resolutions to the issues plaguing Next.Js?

After switching from React to Next.JS, I've encountered some challenges that I'm hoping to find solutions for: In contrast to React, Next.JS doesn't allow me to change a specific part of a webpage and maintain a static element like a navb ...

Guidelines for specifying alternate structures in JSON schema

I have two different JSON file structures, one like this: { "api": "http://my.api.host", "modules": [ "core", "module", "another" ] } and the other like this: { "api": "http://my.api.host", "modules": "*" } The modules attri ...

Tips for implementing asynchronous functionality with the _.some method

Is there a way to utilize _.some() asynchronously? I have the code snippet below that I need to convert to an asynchronous method in order to avoid potential timeout issues. DLClear = async function( obj, squarePt ) { var wallPaths = findObjs( { ...

The antithesis of a feature that encapsulates a chosen area with a span

Hi everyone, I have a function that works as follows: define(function () { 'use strict'; var sel, range, span; return function () { span = document.createElement("span"); span.className = 'highlight'; if (window.ge ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Convert JavaBeans sources into a JSON descriptor

I'm in search of a tool or method to analyze standard JavaBeans source code (featuring getters and setters) and create json descriptors using tools like grunt or ant, or any other suitable option. Here's an example: FilterBean.java: package com ...

Is it possible for Monaco Editor to accommodate nested tokens?

I have configured a custom language in the monaco editor, with two root tokens: [/^\[?[e|E][r|R][r|R][o|O][r|R]\]?\s.*/, 'error'], [/\d{1,4}(-|\/|\.|:)\d{1,2}\1\d{1,4}/, 'time'], Using this ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

The synchronization issue between ng-class and animation

I'm experiencing a strange issue with ng-class and suspect that it may be related to a race condition. Here is the example on Plunker: example Below is the relevant JavaScript code: self.slideLeft = function() { if (self.end_index < se ...

Prompting the website to 'refresh' and return to the beginning of the page

My website's functionality is closely tied to the user's position on the page. Different features are triggered once specific distances are reached. I am seeking a way for users to automatically return to the top of the page upon page reload. Cu ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Why does this particular check continue to generate an error, despite my prior validation to confirm its undefined status?

After making an AJAX call, I passed a collection of JSON objects. Among the datasets I received, some include the field C while others do not. Whenever I try to execute the following code snippet, it causes the system to crash. I attempted using both und ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

What could be the reason for a jQuery script failing to execute when included in a PHP include statement from a different PHP page?

I'm currently working with javascript and php to manage cookies across different pages. On one page, I have a script that sets a value in a cookie variable and I want to retrieve that value on another page. Let's say the first page is named page1 ...

Preserving scroll location in Laravel when posting updates

I am facing an issue with the commenting system in my Laravel application. Whenever a user submits a comment, the page reloads and takes the user back to the top of the page. I would like the page to return the user to the same position where the original ...

Rows that have been removed from an HTML table remain within the ReactDOM

After diving into JavaScript three months ago, I recently began learning React.js just two days back. While creating a simple TODO app, I noticed that when deleting a row, it disappears from the DOM but not from the React DOM. Can anyone shed some light ...

Tips for resolving the error message "An issue occurred with the skill's response" within the Alexa Developer Console

Looking to develop a basic Alexa app where users can interact with voice commands, but encountering an issue with the response in the Test tab of Alexa Developer Console. The error message states "There was a problem with the requested skill's respons ...

Perform queries securely using AJAX when the document is fully loaded

Hello everyone, I'm facing an issue with the custom statistics feature on my website. I collect user data (similar to Google Analytics) and store it in tables for a few months. However, these tables have become too large and are causing slow page loa ...

Implementing a Jquery check based on a checkbox

Hey, I'm having an issue with a condition. When I uncheck the checkbox, it doesn't uncheck. I've tried to make a block display, but the JavaScript isn't working. I attempted to add: document.getElementById("Reload").style.display = "b ...