Two distinct forms featuring inputs that share identical names and ids

I am facing an issue where two forms on the same page have labels with 'for' attributes pointing to checkboxes with identical IDs and names.

When I click a label in the second form, it ends up checking the checkbox in the first form.

The problem arises specifically when clicking the label for 'x name 2', as it checks the 'x name' checkbox even though they belong to different forms:

.customCheckbox div label {
    padding: 5px;
    background-color: white;
    border: 2px solid #aaaaaa;
    background-image: none;
}

.customCheckbox div input {
    margin: 8px auto;
    padding: 5px;
    text-align: left;
    margin-left: -999999px;
    float: left;
}

.customCheckbox input[type=checkbox]:checked ~ label,
.customCheckbox input[type=radio]:checked ~ label {

    background-color: #117399;
    color: #eeeeee;
}

.customCheckbox input[type=radio]:checked ~ label {

    background-color: #117399;
    color: #eeeeee;
}
<form style="margin:30px;">
  <div class="customCheckbox">
    <div>
      <input id="x" name="x" type="checkbox"/><label for="x">x name</label>      
    </div>
    <br/>
    <div>
      <input id="y" name="y" type="checkbox"/>  <label for="y">y name</label>
    </div>
  </div>
</form>
<form style="margin:30px;">
  <div class="customCheckbox">
    <div>
      <input id="x" name="x" type="checkbox"/><label for="x">x name 2</label>      
    </div>
    <br/>
    <div>
      <input id="y" name="y" type="checkbox"/>  <label for="y">y name 2</label>
    </div>
  </div>
</form>

  • I prefer not to change the element names as this is occurring in multiple places
  • Avoiding JavaScript would be preferred if possible
  • Due to using CSS for styling, nesting the checkbox inside the label is not an option (as parent elements cannot be styled in CSS)

Answer №1

You cannot use the same identifier for the ID attribute twice within the same page, regardless of whether the elements are part of the same form or different forms.

However, it is perfectly fine to have multiple elements with the same name property, as names are what get submitted to the server. In fact, you can have numerous elements with the same name within a single form.

The primary function of IDs is to ensure uniqueness on the page. Therefore, it is crucial to assign distinct IDs to each element.

To resolve this issue, you can designate the first element with ... id="x1" name="x" ... and the second one with ... id="x2" name="x" .... Then, adjust your labels to point to either for="x1" or for="x2".

Answer №2

It is perfectly fine for different input fields to share the same name as long as they are part of separate forms or serve the same purpose (e.g. radio buttons).

However, it is crucial to AVOID using the same id for multiple HTML elements.

According to the HTML5 specifications:

The id attribute serves as a unique identifier (ID) for its respective element.

By ensuring that your ids are distinct, your labels will function correctly.

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

Retrieving form output number using JQuery

Hello, I'm new to this site and have no prior experience with javascript coding. Here is what I have in my javascript file: $(document).ready(function() { $("input").click(function(event) { updateTotal(); }); }); function updateTotal() { var to ...

Enhance local rotation of objects in Three.js

I am working on creating a spaceship-like object with controls, and I have learned that I need to use quaternions to achieve this. To start, I am attempting to make a cube rotate to the left when the A key is pressed. Here is the code I have written for th ...

Developing an Angular template component integrated with Express JS backend

I'm encountering an issue while attempting to load a template file from one of my folders in Angular. I have my JS files statically called with Express, however, the template files are not loading. I have tried placing them in the views folder along w ...

What is the best way to remove an object from an array in MongoDB?

I am currently using MongoDB and Node.js, but I am facing a small issue when trying to delete an object from an array of objects. Below is the code snippet causing the problem: router.route('/deleteGuestFromJam/:id').delete(function(req, res){ ...

Exiting a Node.js process using process.exit() may not result in a clean exit, especially when dealing with asynchronous file writing

tl;dr: When using asynchronous fs.writeFile in Node.js from asynchronous events or loops and then calling process.exit(), the files are successfully opened but the data fails to be flushed into the files. It appears that the callbacks given to writeFile d ...

What is the best way to save CSS within a Django class?

Currently, I am in the initial stages of planning a Django application that will generate html5 slideshow presentations. My goal is to have the ability to customize the style of each slide object by defining CSS attributes such as colors and sizes. Additio ...

Discover the steps to retrieve a list of products within a specific category using Vue.js

Hey there! I'm a newbie to vue and I've got myself a bunch of json data that includes products categorized by category. Can someone guide me on how to display each product under its respective category? { "_id": "62566ec30e42d6 ...

What can I do to prevent the text from covering the icon?

My dilemma involves an HTML input alongside a Font Awesome icon. I'm striving to find a way to avoid restricting the amount of text a user can input while ensuring that the text doesn't overlap with .fa-comment-o. Any surplus text should simply b ...

Expanding elements with Flexbox and Bootstrap 4: Strengthening the height to fill the remaining space

I have a row with three columns, each containing an image and a title. Currently, on a large screen, the titles are displayed on a single line and everything looks fine. However, when resizing the screen, the first title wraps onto two lines: My goal is ...

Guide on saving an Express session into a MongoDB database through a controller handling

I'm experiencing a problem with my controller where the session is not being stored properly even after implementing the necessary express session code app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...

The jQuery UI calendar widget fails to include a button on the webpage

I am currently working with a function that I use to add datepickers to dynamically created input elements of type date after wrapping them in $(...). function createDatePicker(inputElement) { inputElement.datepicker({ showOn: "button", buttonIm ...

Can videos be loaded in the front end through JavaScript when dragged and dropped?

I'm working on a project to create a web application that allows users to drag and drop a video file into the browser for processing using TensorFlow.js to make predictions. So far, I've accomplished the following: Loading the video file and p ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Having trouble with filtering the array retrieved from Firebase in Angular?

This is the html: <div ng-controller="FilterController as ctrl"> <div> All entries: <span ng-repeat="entry in ctrl.array">{{entry.from}} </span> </div> <div> Entries that contain an "a": & ...

Exploring ways to extract an element from a newly opened window and set a value using JavaScript

I have been successfully using web_browser.document.getElementById() for the login screen, but I am encountering an issue when trying to use it after logging in and opening a new window. Can someone please assist me with this problem? Below is the code t ...

Python Beautiful Soup Guide for Web Scraping JavaScript Tables with Grid and List Views

Currently, I am attempting to extract data from a json table on a specific website. The URL in question is . I am specifically interested in extracting the name, ratings, and descriptions of all food subscription boxes listed. However, I am encountering ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

Leverage CAPICOM on the Server-Side

I need to convert my code from .net for signing in client side and verifying in server side to asp classic. In the .net code on the client side, I sign with capicom using JavaScript. Here is an example of my code: <script type="text/javascript"> / ...

What is the most effective method to package a React application?

I am currently working on embedding a React application within a Web component's Shadow Root or an iFrame in order to create a widget for a Chatbot messenger similar to Intercom widget. The technologies I am using include: React 16.8.6 Typescript 3. ...