Using TypeScript to effectively validate form checkboxes for input fields

I've created a form that includes multiple checkboxes with corresponding input fields.

<div class="group-wrap input-element" id="gr_">
  <div class="label-bar">
    <label>
      <div class="custom-control form-check">
        <input class="form-check-input" value="1" type="checkbox" id="Gleitzeitmaxstundenenable" name="Gleitzeitmaxstundenenable" onmouseup="{setActFeld(this.id);}" onfocus="{ setActFeld(this.id);}" onclick="{setConfirmedChange(this.id, &quot;false&") ; initCheckBox(this.id);transaktionObj.inputEnable(this.checked,&quot;Gleitzeitmaxstunden&");}">
        <label class="form-check-label" for="Gleitzeitmaxstundenenable">Gleitzeit max.</label>
      </div>
    </label>
  </div>
  <input placeholder="Gleitzeitmaxstunden" name="Gleitzeitmaxstunden" class="form-control text-truncate input-sm zeit-raum withSign numValPicker timecount disabled" data-syntax="-NNN:NN" value="" data-prefix="true" id="Gleitzeitmaxstunden" maxlength="7" type="text" onmousedown="{ if(checkPickerVoll(this.id)){ return false;}else{return (updateZeitMitSign(this,4, false));}}" onkeyup="{  if(checkPicker(this.id)){ return false;} else{return (updateZeitMitSign(this,4, true));}}" onfocus="{ setActFeld(this.id);}" onkeydown="{ if(checkPickerVoll(this.id)){ return false;}else{return (updateZeitMitSign(this,4, false));}}"...

Whenever a checkbox is ticked and the user inputs a value in the corresponding field, the TS method should confirm as true.

        let fehler = false;
        $JQ("input.form-check-input").each(function(ind: number, checkBox: Element){
            const checkbox = $JQ(checkBox);
            const inputId = checkbox.attr("id").replace("enable", "");
            
            if($JQ(`#${inputId}`).val() !== ""){
                fehler = true;
            }
        });
       
        return fehler;

However, the condition $JQ(#${inputId}).val() !== "" always results in true. I would appreciate any assistance provided.

Answer №1

When a checkbox is altered, the input element's required property will be toggled between true and false.

The form submission will only occur if all mandatory fields are valid - for instance, containing any value. To specify more specific requirements, attributes like pattern, minlength, or maxlength can be utilized for text inputs (

<input type="text">
).

document.forms.form01.addEventListener('input', e => {
  let form = e.target.form;
  let elm = e.target;
  
  switch(elm.type){
    case 'checkbox':
      form[elm.dataset.name].required = elm.checked;
      break;
  }
});

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  console.log('submitting');
});
fieldset {
  border: none;
}
<form name="form01">
  <fieldset>
    <label><input type="checkbox" data-name="text01"></label>
    <label>Text 01: <input type="text" name="text01"></label>
  </fieldset>
  <fieldset>
    <label><input type="checkbox" data-name="text02"></label>
    <label>Text 02: <input type="text" name="text02"></label>
  </fieldset>
  <fieldset>
    <label><input type="checkbox" data-name="text03"></label>
    <label>Text 03: <input type="text" name="text03"></label>
  </fieldset>
  <button type="submit">Submit</button>
</form>

Answer №2

When working with JavaScript, it is important to remember to evaluate the checked attribute instead of the value attribute when dealing with checkbox inputs.

This means that you should use the following code:

document.getElementById(inputId).checked;

If you are using jQuery, the equivalent code would be:

$(`#${inputId}`).is(":checked");

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

Tips for troubleshooting JSONP AJAX events

I've been encountering some issues with a JSONP AJAX request that I'm trying to make. Despite my attempts to troubleshoot, the request doesn't seem to work as expected. Here is the code snippet that I've been using: $.getJSON(server_pa ...

Issue: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin is a required field and must be provided

While developing my Shopify App using Koa and Nextjs, I encountered the following error: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin must be provided The behavior of the app is a bit odd as it works fine when accessed for the first time. Howev ...

What purpose does Webpack serve in injecting React?

Within my webpack entry file, I have the following code snippet: import ReactDOM from 'react-dom'; import Layout from './components/Layout'; // ... dialog = document.createElement("dialog"); ReactDOM.render(<Layout dialog={dialog} ...

Stop touchCancel during scrollStart action

When using an Android device, a scroll event triggers a `touchcancel` event, which prevents the touch up event from being triggered after scrolling. To avoid the `touchcancel` event, I implement a `preventDefault` on `touchStart` within the scrolling div. ...

How can you personalize the background color of a Material-UI tooltip?

Is there a way to customize the hover tooltip with a "? icon" for users providing input guidance in a text field? I prefer the design to have white background with grey text and larger font size, as opposed to MUI's default style which is grey with wh ...

Using Driver Wait Until Text in Selenium involves waiting for a specific text to appear on a

I'm currently experimenting with the driver wait function using this specific wait condition. My goal is to verify that the text displayed on a button is exactly "Sign Up". Below is the code snippet I am working with: driver.wait(until.elementTextIs( ...

I am looking to use jQuery to update certain elements on the Cart details page to give it

I'm facing an issue with updating the page properly after clicking Remove from Cart. The item is removed from the cart table, but it still appears on the screen. I need a command to partially refresh the screen after executing my jQuery. Thank you f ...

The `findOne` operation in Mongoose fails to complete within the 10000ms time limit

Encountering this error on an intermittent basis can be really frustrating. I am currently using mongoose, express, and typescript to connect to a MongoDB Atlas database. The error message that keeps popping up reads as follows: Operation wallets.findOne() ...

Can NgFor accept dynamic keys as variables?

'Keys' (keys: any;) represent the headers extracted from 'data.items[0]' using the 'object.keys' method. How can I properly loop through the objects in 'data.items'? Using *ngFor does not seem to work as expected. ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

What is the best way to transfer a file from the "src" directory to the "public" directory in JavaScript?

I am currently working on developing a single-page application (SPA) / progressive web app (PWA) using Vue Js. One challenge I am facing is importing a file of functions from the 'src' folder to the 'public' folder in my project direct ...

Implementing two-dimensional orientation on particles in three.js

My first attempt at using three.js involves a basic particle animation with 4 different textures mapped onto them. Everything is working smoothly so far, except for one issue - I can't seem to rotate the particles randomly for different orientations ( ...

Is left padding appearing mysteriously (supernatural CSS phenomenon)?

While using the Firebug inspector tool, if you hover over #jimgMenu ul, you may notice that it has left padding without any corresponding CSS rule: Where is this mysterious left padding coming from? Why is the origin not visible? EDIT: If you navigate t ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

Tips for utilizing JSON and ajax smoothly without encountering any errors

I am attempting to retrieve JSON data from an external PHP file using AJAX and populate it into a dropdown list. After successfully setting up XAMPP with Apache and Mysql, I managed to make everything work for one JSON object. However, when I tried adding ...

What are the steps to developing a unique JavaScript function?

Recently, I created a new function. function createGarage(id) { var id = 'data.models.'+id+'.pictures'; $.ajax({ url: 'models.json', type: 'get', dataType: 'json', error: function(data) ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

MUI provides the flexibility to adjust the opacity separately for Chip labels/icons and backgrounds

My objective is to customize the opacity of label/icon and background in MUI Chip. I want the label & icon to have an opacity of 1, while the background should have an opacity of 0.0571. Technologies used in this project include React, TypeScript, Materia ...

Sometimes, the submission of a form using jQuery/Ajax only seems to be successful every second attempt

I'm having trouble with submitting a form that involves file upload using Ajax/jQuery, processing it through a PHP script, and displaying the result in the original div where the form was located. Here is my current form code: <section id="conten ...