I have multiple forms created using for loop and I'm passing the field Id which is unique for all forms and fields to the javascript method but it is not reading the value using id.
Any other way to send the id so that I can get the exact field value in the javascript for ajax processing. Any help would be much appreciable.
<%
String js = "Id" + count;
%>
<input name='Id' label="" id='Id<%=count%>' style="width:100px;" onChange="javascript:getName('<%=js %>')" />
function getName(count) {
String field = count;
var field1 = document.getElementById(field).value;
alert(field1);
}
Whereas field1 is showing null
First of all the following code String field = count; is incorrect you need to replace String by var because this is how JavaScript variables declartion work, but anyway you can get rid of this line.
And your JS will be:
function getName(count) {
var field1 = document.getElementById(count).value;
alert(field1);
}
Optimisation:
Note that you can pass the id directly in your JSP like this:
<input name='Id' label="" id='Id<%=count%>' style="width:100px;" onChange="javascript:getName(this.value)" />
And in your JS:
function getName(count) {
alert(count);
}
You need to do it like this
function getName(count) {
// String field = count;
var field = count;
var field1 = document.getElementById(field).value;
alert(field1);
}
Javascript supports creating variables by using the var keyword not the String.
You can use
onChange="javascript:getName(this)"
And in javascript
function getName(ref) {
var id= ref.id;
alert(id);
}