Tips for validating certain input fields within a designated div container

Is there a way to validate only specific fields within a div, rather than all fields? Take a look at this jsfiddle for an example. Once validation is passed, I want the div to be hidden. However, I do not want to include certain fields such as the input field that appears when 'Yes' is checked on the checkbox. Similarly, selecting 'NoGame' from the dropdownlist should exclude two fields in the lower div (green border) from the validation process. Any suggestions?

Below is the code that validates all fields and hides the div, as demonstrated in the fiddle.

  function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
$.each($div.find("input[type='text']"), function (i, input) {
    if ($(input).val().length == 0 || $.trim($(input).val()) == '') {
        result = false;
        return;
    }
});

return result;
  }

  $(document).ready(function(){
             $("#hide").click(function(){
                if (IsValid('contentone')) {
$('#contentone').hide();
 };
             });
         });

Answer №1

To bypass validation for input fields of type text that you do not wish to validate, simply exclude them from the validation process

function CheckValidity(divId) {
var $division = $('#' + divId);
var outcome = true;
var excludedElements = ["reason"]; //<-- IDS OF ELEMENTS TO BE EXCLUDED
$.each($division.find("input[type='text']"), function (index, inputField) {
    if ($.inArray($(inputField).attr('id'), excludedElements) < 0 && ($(inputField).val().length == 0 || $.trim($(inputField).val()) == '')) {
        outcome = false;
        return;
    }
});

return outcome;
}

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

Transitioning an Angular dropdown from static data to dynamic data fetched from a live service

I am facing a challenge with my Angular 5 dropdown. It currently works well with hard coded data, but I now need to switch it to live data. The issue is that the live data I have is in plain array format. Here is how it currently functions HTML <sele ...

Is the isPointToPath function unreliable in JS/CANVAS/HTML?

Check out the snippet below for testing purposes. The yellow(y) area represents the canvas, returning "n" upon clicking The red(r) area represents the clickable region, returning "y" upon clicking The trouble(x) area indicates an error, returning "y" wh ...

Convert user input from an azerty keyboard to Arabic characters automatically using JavaScript

My goal is to create a JavaScript code that can: 1. Accept a character input from a user in an HTML form text field. 2. Retrieve the keyCode of the entered character. 3. Display a corresponding Arabic character based on the acquired KeyCode. For in ...

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

Searching for every link on the page in order to compile a comprehensive list

How can you extract all links (excluding anchors) and organize them into a list, maintaining their original order, using jQuery? For instance: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet ipsum ut justo fermentum hendrerit ul ...

"Enhance your experience by multiplying items with just a click on a designated list item + using

I am facing a major issue that I can't seem to resolve. I am using Leaflet to display a map combined with AJAX. When I click on a country, a list of "customers" is displayed. However, when I click on a specific customer for more information, the custo ...

Upon attempting to utilize Socket.io with Next.JS custom server, the server repeatedly restarts due to the error message "address already in

Every time I attempt to execute the refreshStock() function within an API endpoint /api/seller/deactivate, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (net.js:1318: ...

Guide on using webpack to import jQuery

When using webpack, is it necessary to install the jquery file from npm, or can I simply require the downloaded file from the jquery website? directory app/ ./assets/javascripts/article/create/base.js ./assets/javascripts/lib/jquery-1.11.1.min.js webpack ...

What is the best method for retrieving the array response in Node.js after finishing the foreach loop?

I have encountered an issue with my code where it is returning an empty array after running a foreach loop and trying to send data to the client. The problem seems to be related to the global declaration of a variable. Specifically, I need to push the loan ...

The radio button is not appearing correctly in my HTML form

Seeking guidance as a newcomer to html and css. Looking to create a signup form using html and css, but encountering issues with the radio button not displaying in the browser. Unsure of the root cause of the problem. Any assistance would be greatly apprec ...

Error: The property 'postID' can not be read because it is undefined

I'm new to programming and I am working on creating a news/forum site as a practice project. I have set up a route /post/postID/postTitle to view individual posts. Initially, when I used only :postID, it worked fine. But after adding :postTitle, whene ...

Incorporating a weather widget into the information window of a Google map

I am having some trouble trying to integrate a weather widget from into an Info Window on a Google map. The goal is to have the weather widget open in the Info Window when a marker on the map is clicked. The code snippet for embedding the weather widget ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

What could be causing the tooltip to malfunction in jQuery?

The tooltip is not appearing as expected, only the title is displaying in the browser. What can be done to fix this? Below is the code snippet: HTML Code: <form action="/validate.php" method="post" id="myform"> <table width="100%" border="1"> ...

Set the page to be rigid instead of flexible

I'm struggling to lock this webpage in place, so it doesn't resize when the browser window changes. The text keeps collapsing whenever I adjust the size of the browser, and I can't figure out what's going wrong. Can someone please help ...

Retrieving a JavaScript variable from a different script file

I have a JavaScript script (a) with a function as follows: function csf_viewport_bounds() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); var maxLat = ne.lat(); var maxLong = ne.lng(); ...

Display a loading message before fetching remote data in the Bootstrap modal box

Here is the code I am using to load remote PHP data into a Bootstrap modal box: $(function() { $(window).bind("resize", function() { if ($(this).width() < 400) { $('#tabs-content').removeClass('col-xs-10').ad ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...

How can I retrieve the transformation matrix for a DOM element?

Is there a way to retrieve the transformation matrix of a DOM element similar to how we can do it with canvas context? Does the DOM provide a getTransform() method for this purpose? ...

Truncating decimal points in JavaScript

In this scenario, if the number after the decimal point is 0, then the zero should be removed. Otherwise, the number should be displayed as it is. Here are some examples of what I am aiming for in vue: 100.023 => 100.023 1230.0 => 1230 ...