Angel Vasilev
Angel Vasilev

Reputation: 77

Two forms on one page with same input fields

So I have 2 identical forms on a page which I cannot give different names, because they are tied to the back-end.

I have a few input fiends with same ID's on the diferent forms, which are checked if they are empty with document.getElementById('id').value;

Strange thing is, half of the input fields are checked on one of the forms and the other half are checked from the other form (this is when the user is entering values in only one of the forms), despite them using 2 different javascript functions. For one input field it gets the closest id automatically, for the others it goes all the way up to the other form.

My question is how can I get the value of the elements to be checked which are closest to the submit button (or other element near one of the forms)?

I tried with the jQuest closest() method, but I can't seem it to get to work with all of the document.getElementById.

Upvotes: 1

Views: 2450

Answers (1)

Tom O.
Tom O.

Reputation: 5941

Element IDs should always be unique. You should never have 2 or more elements with the same ID. document.getElementById('someId') is expecting to return 1 element, not an array of elements - there are other functions available if you want to get multiple elements that dont require you to duplicate IDs.

From w3schools:

An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.

More about HTML DOM getElementById() Method

Upvotes: 2

Related Questions