talhaMalik22
talhaMalik22

Reputation: 155

Document.getElementById.value returning Undefined

Following is my HTML code

<div id="dl_address" class="dl-row">
 <div class="dl-col1">
    <span id="dl_addressMarker" class="dl-Marker">*</span>Address:
 </div>
 <div class="dl-col2">
  <input  id="dl_addressMarker" name="p.streetAddress" maxlength="100" size="15"  
                            class="landing-qualpanel-input-standin" type="text" onClick="formOpt(id)" value="Home Address">
 </div>
</div>

And Following is my javascript code

<script language="javascript" type="text/javascript">
function formOpt(x){

    var y=document.getElementById(x).value;
    alert(y);
    }
</script>

I can't understand why i am getting Undefined. Kindly Help. Thanks in advance

Upvotes: 0

Views: 10102

Answers (3)

gideon
gideon

Reputation: 19465

You have 2 problems. (1) you should call your method like this: formOpt(this) which will pass the current element in. (2) You have repeated DOM ids.

Write is like this:

<script language="javascript" type="text/javascript">
function formOpt(x){
    //x is now the input element. You can fetch its id property.
    var y=document.getElementById(x.id).value;
    // you can do other things with x also.
    alert(y);
    }
</script>
<div id="dl_address" class="dl-row">
 <div class="dl-col1">
    <span id="dl_addressMarker" class="dl-Marker">*</span>Address:
 </div>
 <div class="dl-col2">
 <!-- I renamed the id on the input -->
  <input  id="dl_addressMarker_input" name="p.streetAddress" maxlength="100" 
  size="15"  class="landing-qualpanel-input-standin" 
 <!-- pass this into the function -->
  type="text" onClick="formOpt(this);" value="Home Address">
 </div>
</div>

See working sample: http://jsfiddle.net/KXCeh/1/

Upvotes: 2

Ankit
Ankit

Reputation: 690

you need to pass the value of id, and you also need to keep the ids unique for each and every element

            <div class="dl-col2">
  <input  id="dl_addressMarker" name="p.streetAddress" maxlength="100" size="15"  
                            class="landing-qualpanel-input-standin" type="text" onClick="formOpt('dl_addressMarker')" value="Home Address">
 </div>

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

That's because you have two elements with the same Id, which isn't allowed in HTML and which makes it impossible for your function to get the input this way.

Change the id of your input and you'll be fine.

You could simplify the code by passing the element and not the id :

HTML :

<input  id="dl_addressMarker2" name="p.streetAddress"
      maxlength="100" size="15"  
      class="landing-qualpanel-input-standin" type="text"
      onClick="formOpt(this)" value="Home Address">

JavaScript :

function formOpt(x){
   var y = x.value;
   alert(y);
}

Upvotes: 3

Related Questions