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.
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.
Share Improve this question edited Dec 15, 2016 at 16:24 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Dec 15, 2016 at 16:12 Nimble FungusNimble Fungus 5484 silver badges23 bronze badges4 Answers
Reset to default 4Since 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.
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();
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 mon 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.
The W3C standards for HTML require the id to be unique in a document.