Generate an error upon submission if a particular checkbox is chosen from a group of checkboxes

To prevent form submission and display an error message if checkbox id="check1" is selected, follow the code below:

<form name="form1" method="post" action="">
    <span id="group">
        <input type="checkbox" name="check1" id="check1" value="1">
        <label>check1</label> <br>
        <input type="checkbox" name="check2" id="check2" value="2">
        <label>check2</label> <br>
        <input type="checkbox" name="check3" id="check3" value="3">
        <label>check3</label> <br>
        <input type="checkbox" name="check4" id="check4" value="4">
        <label>check4</label> <br>

        <span id="error-message" class="error" style="display: none;">One or more of your selection is wrong.</span>
    </span>
    <input name="submit" type="submit" value="submit" onclick="validateForm()">
</form>

Answer №1

When using jQuery,

Your JavaScript code would look like this:

$('input[name="submit"]').on('click', function(e){
    if( $('input#check1').is(":checked") ){
        e.preventDefault();
        $('span.error').removeClass("hide");
    }   
});

This is the HTML part of it:

<span class="error hide">There seems to be an error in your selection.</span>

Also, here's the CSS for hiding the error message:

   .hide{
       display: none;
   }

If you want to see how this code works, check it out on JSFiddle:

JSFiddle

Answer №2

To begin, ensure that your submit button is of type 'button' and assign a JavaScript function to its onclick event as demonstrated below:

<input name="submit" type="button" value="Submit" onclick="validateSubmission()">

// JavaScript function
<script type="text/javascript">
    function validateSubmission() {
        var checkboxChecked = document.getElementById('check1').checked;
        if (checkboxChecked) {
            // Display error message using span element
        } else {
            // Submit the form programmatically
            var forms = document.getElementsByName('form1');
            forms[0].submit();
        }
    }
</script>

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

Extension for Chrome that switches between active and inactive modes

I have been attempting to create an extension that can toggle the functionality of another specific extension on and off. Despite numerous attempts, I have not been able to find a solution that works effectively. Essentially, my extension displays a popup ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

Index similar to JavaScript-Meadow

Is there a way to create a table of contents like the ones seen on sites such as JavaScript Gardens? How do they determine which section is currently active and are there any recommended JavaScript libraries that can help achieve this functionality? Edit: ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

Rectangles in collision: A mathematical analysis

After numerous attempts, I have developed a small "game" that incorporates collision detection. Unfortunately, I have encountered a persistent issue where objects sometimes pass through each other. The root cause of this problem eludes me completely. Ini ...

alter information in a javascript document

Hey there, I've got a JavaScript array of URLs in my content.js file. I want to show these URLs in separate input boxes on a different page called display.php. Each input box will have edit and delete buttons. Any changes made by the user should updat ...

An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it. HTML <html> <head> <link href="index.css" rel="stylesheet"> </head> <body> <div id="r ...

trigger opening a bootstrap modal programmatically

I have a modal setup using Bootstrap with the code below: <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true" > &l ...

Discover additional and subtract options

I am trying to implement a "See more" and "See less" button functionality for my list items inside an unordered list using the code below, but it is not working as intended. $(document).ready(function() { var list = $(".partners__ul li"); var numTo ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

There is an issue with the functionality of Java code that has been adapted from Javascript logic

I'm currently using NetBeans8 IDE. Check out this java script function from this Fiddle function animate() { xnow = parseInt(item.style.left); item.style.left = (xnow+1)+'px'; ynow = parseInt(item.style.top); item.style. ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Ensure the Firebase real-time database in Javascript purges the active session upon tab or browser closure

I need to implement a feature in my Firebase real-time database project using JavaScript where the current session is logged out automatically after closing the tab or browser. When I log in with my email and password, if I copy the URL and paste it into ...

What could be causing my Angular JS application to malfunction?

Presenting myFirstAngularApp.html <html ng-app="store"><!-- The "ng-app" attribute initializes an Angular app. Everything inside this tag is considered part of the Angular app due to ng-app --> <head> <link rel="stylesheet" type= ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...