Reputation: 548
I have two form on same page. There is a text field with same name in both of the forms.
I am tried to read the value of the text field from one of the two forms. if I am trying to read the value using below code i am getting the value . But I am not sure from which forms it is returning the value.
document.getElementById("groupId")
Now if I am trying to read the value from specific form using below code I am receiving the error.
document.forms["form1"].getElementById("groupId")
Please suggest whats wrong I am doing and how can we read the value of a control ?
I can use both javascript and jquery.
Upvotes: 2
Views: 2170
Reputation: 134
The W3C standards for HTML require the id to be unique in a document.
Upvotes: 0
Reputation: 19007
if i am trying to read the value using below code i am getting the value . But i am not sure from which forms it is returning the value.
This means you have multiple elements with same id
which is a big NO. id's
are supposed to be unique in your entire HTML. If for some reason you want to use same id
on multiple elements to work with JavaScript be aware the same task is possible by assigning same class
to the elements and accessing by class
Having said that, Change your HTML to not have duplicate id
and change them to have a common class. Now with this structure you can access the element starting from your from
like below
$('form[name="form1"]').find('input.ClassName').val()
Also for info purpose
: If you have multiple elements with same id
in your HTML and when you try to access by id
the element which is placed in top parsing from top will be selected always.
Upvotes: 2
Reputation: 67525
Since you're using jQuery you could do :
$('[name=form_name]').find('#field_id');
Your case e.g :
$('[name=form1]').find('#groupId');
Using pure js you could do it like :
document.form_name.getElementById("field_id");
Sample of your case :
document.form1.getElementById("groupId");
Hope this helps.
Upvotes: 4
Reputation: 11377
You can do the following with jquery
.
var element = $(document.forms["form1"]).find('#groupId')
And to get the text value you can use the val
function.
var text = element.val();
Upvotes: 2