Ways to require text entry only when specific radio buttons are selected in jQuery

Currently, I am working on a project using JSP and have created an HTML form with a Process button at the top. When this button is clicked, a form is displayed containing two radio buttons - TestClient and TestServer.

The form also includes a Submit button for submitting the data.

To view the JSFiddle related to this, click here.

My goal is to require users to fill in the firstName and lastName textboxes when selecting the TestClient radio button before they can press the Submit button. Any additional information entered into a third textbox for the TestClient radio button should trigger an error message next to that specific textbox. On the other hand, if the TestServer radio button is selected, all three textboxes must be filled out.

I am considering implementing a disable feature for the Submit button if certain conditions are not met, along with displaying a relevant message next to the textboxes.

Although I am new to jQuery, I am eager to learn more about it and its functionalities.

Answer №1

To simplify user interaction and prevent confusion, consider using the hide() function to hide unnecessary fields like demonstrated in this sample code. By hiding the address field when the TestClient button is selected and showing it when the TestServer button is chosen, you can streamline the input process and reduce the likelihood of error messages popping up, which users typically find frustrating.

Answer №2

check out this interactive example

If you want to determine if a form can be submitted, use a submittable method to check if required inputs have a value:

// update submit button
function submittable() {
    // retrieve all required fields (needs to be done each time)
    var $required = $('input[required=required]', '#form_process'),
        $submittable = true;
    
    $required.each(function() {
        if ($(this).val()) {
            // do nothing
        } else {
            $submittable = false;
        }
    });
    return $submittable;
}

To make this work correctly, ensure that your universally required inputs have the required attribute and your optionally required address input does not have it.

<input name="fname" id="fname" placeholder="firstName" required="required">
<input name="lname" id="lname" placeholder="lastName" required="required">
<input name="address" id="address" placeholder="address">

Next is the validate method which uses the submittable function to validate the form and enable/disable the button accordingly:

var $submit = $('#submit');

// control validation
function validate() {
    if (submittable()) {
        // valid state
        //alert('valid');
        $submit.attr('disabled',false);
    } else {
        // invalid state
        //alert('invalid');
        $submit.attr('disabled',true);
    }
}

Initially, run the validate function:

// perform initial validation
validate();

Then, trigger it on keyup of any form input:

// validate on input keyup
$('#form_process input').keyup(function() {
    validate();
});

You also need a function to get the currently checked radio option to show/hide additional input. Make sure to toggle the required attribute for the address input when needed so it's included in the validate method:

var $address = $('#address'),
    $server = $('#server');

function getChecked() {
    // identify currently selected input
    var $checked = $('input[name=client]:checked', '#form_process');
    // if server is selected
    if ($checked.attr('id') === 'server') {
        //alert('server!');
        $address.show();
        $address.attr('required',true);
    } else {
        //alert('client!');
        $address.hide();
        $address.attr('required',false);
    }
}

For this to function properly, set one of the radios as checked initially:

<input type="radio" name="client" id="client" value="TestClient" checked="checked">TestClient 
<input type="radio" name="client" id="server" value="TestServer">TestServer

Call the getChecked function at the beginning and whenever a radio selection changes (along with running the validate method):

// initial get checked call
getChecked();

// for each radio
$('input[type=radio]').each(function() {
    // when selection changes
    $(this).change(function() {
        // get checked radio
        getChecked();
        // perform validation
        validate();
    });
});

note

This solution is specific to this particular problem. If you have more than 2 radios with different input scenarios, the getChecked() function may require adjustment.

Additionally, $('input[type=radio]').each() should be more targeted if there are multiple radio groups. In such cases, consider adding a class to each radio or wrapping them in a parent element to differentiate them.

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

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

The package-lock file may vary depending on the npm version being used

I am experimenting with a new typescript react app that was created using CRA. I am running @6.4.1 on one PC and an older version on another. Interestingly, the newer version installs dependencies with an older version instead of the expected new one. ...

When looking at the table, it will only read integer values for EmpID. However, if it is a string value

This method on a website uses AJAX and jQuery. When the EmpID is in the format of 123, 12, or 123456, it opens a popup box and displays the desired output. However, when the EmpID is in the format of A001 or ABC, it displays an error message saying "Error ...

What are the steps to view output on VS Code using Typescript?

Currently, I am working on code challenges using Typescript in Visual Studio Code. However, whenever I attempt to run the code and view the output, I encounter an error stating "Code Language is not supported or defined". I have already set the language ...

Superimpose one element on top of another

My current page layout includes the following code: <div class="card"> <div class="card-block"> <h4 class="card-title text-muted">UltimateWarrior15</h4> <h6 class="card-subtitle text-muted"> Ad ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

Issue with component not updating upon state change

Having trouble getting my react function component to rerender immediately after updating the state. The application takes input for material cost of each product and calculates the total. I want the component to display the updated total as soon as the i ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Template for event cell details in Angular2 calendar view

Currently utilizing [angular-calendar] from github.com/mattlewis92/angular-calendar . My goal is to incorporate my own template as a detailed view for events. I am aiming to achieve a similar effect as shown in the image: final effect So far, I ha ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Question about HTML Class. Explain the meaning of the hyphen (-) in a class

https://i.sstatic.net/wCbvo.png When looking at this image, is the '-' symbol serving as a connector between two ids or is the entire 'fa-facebook' considered an id? ...

Displaying an element when hovering over another using CSS

Currently, I am experimenting with a small CSS action that involves displaying another element when an A element is hovered over. The code I have so far is quite simple: <a title="#" class="portfolio-reaction" href="#"> <img src="http://i.imgur.c ...

How can DataTables (JQuery) filter multiple columns using a text box with data stored in an array?

I've been attempting to create a multi-column filter similar to what's shown on this page () using an array containing all the data (referred to as 'my_array_data'). However, I'm facing issues with displaying those filter text boxe ...

Unable to manipulate the marker with the leaflet library

Currently, I am utilizing react.js with the leaflet library and would like to enable marker movement on the map when clicked, instead of adding a new one. Below is the code snippet I am working with: import React from "react"; import { MapConta ...

What is the reason behind the body element's background styling impacting the entire screen?

Why does styling the background of the body element affect the entire screen instead of just the body itself? For example, consider this CSS rule: body { width: 700px; height:200px; border: 5px dotted red; background-color: blue; } While the ...

Once the fields have been reset using .val(''), they will remain empty until the page is refreshed

I have implemented Bootstrap Modal in my document to dynamically load a document. Within this Modal Window, I use ajax to store the values of two form fields into the database. Upon successful request, I reset the two form fields using .val(''). ...

Leverage the power of jQuery scripts in Django templates by making use of the

I am interested in using the script available at , but it seems that the syntax used in the code involves {{ }} which Django is unable to interpret correctly. Is there a way to instruct Django to ignore these specific lines of code and not attempt to inser ...

Merge the movements of sliding a block along with the cursor and refreshing a sprite displayed on the block

Confronted with the challenge of combining 2 animations, one to move the block behind the cursor inside the container and the other to update the sprite on the block. Let me elaborate further on my issue. The block should only move when the cursor is insi ...

Troubleshooting issue: Failure in proper functionality of Jquery's slideDown

My form is divided into 3 sections, with the latter two initially hidden using CSS. When users click the next button in the first section, the second section is supposed to slide down into view. However, I'm experiencing an issue where the animation s ...

Combine NPM dependencies into a single JavaScript file

Attempting to integrate Swig, a template language, into Parse Cloud Code with Express can be quite challenging. Parse Cloud Code is a Node/Express host that has restrictions on using NPM, which can be frustrating. However, there may still be a way to load ...