methods for verifying changing row array data in javascript

Can someone please provide guidance on how to validate the array values in JavaScript? Below is the code I am currently using. The issue I am facing is that even after filling up all the values, I still receive a validation error message. Please advise me where I may be going wrong.

function chkdate() {
    var x = document.forms["main"]["date"].value;
    if (x == null || x == "") {
        document.forms["main"]["date"].focus();
        document.forms["main"]["date"].style.background = 'red';
        alert("Date Cannot be empty");
        return false;
    }
}

function chkempty() {
    var len = document.forms["main"]["item[]"].length;
    if (len == undefined) {
        var ic = document.forms["main"]["item[]"].value;
        var iq = document.forms["main"]["qty[]"].value;
        var ip = document.forms["main"]["price[]"].value;
        if (ic == null || ic == "") {
            document.forms["main"]["item[]"].focus();
            document.forms["main"]["item[]"].style.background = 'red';
            alert("Item Cannot be empty");
            return false;
        }
        if (iq == null || iq == "") {
            document.forms["main"]["qty[]"].focus();
            document.forms["main"]["qty[]"].style.background = 'red';
            alert("Qty Cannot be empty");
            return false;
        }
        if (ip == null || ip == "") {
            document.forms["main"]["price[]"].focus();
            document.forms["main"]["price[]"].style.background = 'red';
            alert("Price Cannot be empty");
            return false;
        }
    } else for (i = 0; i < len; i++) {
        var ica = document.forms["main"]["item[]"][i].value;
        var iqa = document.forms["main"]["qty[]"][i].value;
        var ipa = document.forms["main"]["price[]"][i].value;
        if (ica == null || ica == "") {
            document.forms["main"]["item[]"][i].focus();
            document.forms["main"]["item[]"][i].style.background = 'red';
            alert("Item Cannot be empty");
            return false;
        }
        if (iqa == null || iqa == "") {
            document.forms["main"]["qty[]"][i].focus();
            document.forms["main"]["qty[]"][i].style.background = 'red';
            alert("Qty Cannot be empty");
            return false;
        }
        if (ipa == null || ipa == "") {
            document.forms["main"]["price[]"][i].focus();
            document.forms["main"]["price[]"][i].style.background = 'red';
            alert("Price Cannot be empty");
            return false;
        }
    }
}

Additional details:

Form name: main The input boxes item, qty, and price are dynamic rows based on the user's requirement. Thank you all.

Answer №1

To enhance your form validation, I highly recommend utilizing jQuery in combination with the validate plugin.

Below is an example that has proven effective for me:

$("#testform").validate({
    rules: {'qty[]': {required: true,minlength: 1},
    //other rules here
},
messages: {
    'qty[]': "Select at least one qty",
    //other custom error msgs go here
}
});

<input name="qty[]" id="1" value="1" type="checkbox" /> 
<input name="qty[]" id="2" value="2" type="checkbox" /> 
<input name="qty[]" id="3" value="3" type="checkbox" /> 

Note that it is important to specify the name of the field of array values with quotes ('qty[]') to avoid any JavaScript errors.

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

Invoke a TypeScript function within JavaScript code

As a result of the limitations of IE10 and earlier versions, I find myself in need to reimplement the Import/Upload functionality that I had initially created since FileReader is not supported. After some consideration, I have opted to utilize an iFrame in ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Teaching how to utilize Express to send a blob object as a response

Currently, I am utilizing Express and TrueVault to store images on my server. When I receive a blob object from the TrueVault API, it appears as follows: { blob: Blob { [Symbol(type)]: 'image/png', [Symbol(buffer)]: <Buffer 89 . ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Change all instances of the subtraction symbol to parentheses using jQuery

--html-- <table> <tr> <th>a</th> <th>b<th> </tr> <tbody class = "tabledata"> <tr>a</tr> <tr>b</tr> </tbody> </table> --jquery-- $('.tabledata').empty(); for ( ...

Meteor: The call stack has surpassed its maximum size limit

I attempted to perform an action that I have done several times before without encountering any errors. My goal is to retrieve all documents where the X field matches the value Y in my Meteor app: JS: (template helper) 'friendPictures' : funct ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...

Map will be visible correctly only when the window is resized

I'm currently working on a project that utilizes a map engine from a private company which I am unable to disclose. The initial system was built in JQuery, but we recently underwent significant changes and now have it running on AngularJS. One side ...

Methods for displaying a placeholder in a semantic-ui-vue dropdown without using the multiple attribute

When utilizing the dropdown feature in semantic-ui-vue, I have encountered an issue where the placeholder option does not function unless the multiple attribute is included. You can view my sandbox demonstration at this link. I have set up 2 dropdowns: ...

Implementing dotenv in a Node JS package

I'm in the process of developing a Node application that retrieves search results through a Google Custom Search Engine (CSE). To streamline the process, I plan to extract the component responsible for sending requests to Google and receiving the res ...

Is it possible to deceive Array.isArray?

Although I have a good understanding of prototypes, I encountered some confusion when I attempted the following: var obj = {}; Object.setPrototypeOf(obj, Array.prototype); console.log(Array.isArray(obj)); // false? What's even more perplexing: var ar ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

Adding the Load More feature to your WordPress template for displaying custom posts

On my website, I am retrieving posts of a custom post type using get posts. However, I am retrieving all posts at once, but in my template, I want to display x number of posts per page and load the remaining posts using a load more button. <?php ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

Learn the steps to showcase the output in a paragraph using ReactJS

Is there a way to display the result in the browser instead of just exporting it to the console when using the code below? I am new to React and would like the result to appear in a paragraph or another tag on the webpage. import React, { Component, use ...

What could be causing my array to be undefined upon the creation of a Vue component?

I'm struggling to comprehend why my array is showing as undefined in my Vue component. The issue arises in the following scenario: The SelectCategories.vue component uses the router to navigate to the Quiz.vue component. Here, I utilize props to tran ...

"Discovering the referring page URL in Next.js: A Step-by-Step

On a webpage, I use router.push('destination-url') to redirect users to an external link. I want to determine if the user has navigated back from the redirected page or not. If they arrived from an external link, they should not be allowed to re ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Is there a way to detect when a Bootstrap Alert is displayed?

I am using a flask app that flashes messages to an HTML file. When these flashed messages are caught, they are displayed as a bootstrap alert. Here is an example: {% with messages = get_flashed_messages() %} {% if messages %} {% for message in mes ...