ssshekhawat
ssshekhawat

Reputation: 101

how to access an text value

in the following piece of code i want to access input text box value using your id. but it's throwing an object error.

<HTML>
<HEAD>
<script>
function test()
{
 var a1 = document.getElementById(i1);

 alert(a1);
}
</script>
</HEAD>

<BODY>
<div id= 'test1'>
<div id = 'test2'>
        <input id = 'i1' type = 'text' name='i1' value='random'>
        <input type='button' value="click me" onclick="test()">

    </div>
</div>

</BODY>

Upvotes: 0

Views: 190

Answers (5)

shyammakwana.me
shyammakwana.me

Reputation: 5752

change

var a1 = document.getElementById(i1);

to this

var a1 = document.getElementById(i1).value;

OR you can change

alert(a1);

to

alert(a1.value);

Upvotes: 0

Ganesh Rengarajan
Ganesh Rengarajan

Reputation: 2006

Example1

function test() {
 var a1 = document.getElementById('i1').value;    
 alert(a1);
}

Example2

<input type='button' value="click me" onclick="test(document.getElementById('i1').value)">

 function test(a1) {
  alert(a1);
}

FULL HTML CODE

  <HTML>
  <HEAD>
   <script>
    function test()
    {
    var a1 = document.getElementById('i1').value;

    alert(a1);
    }
   </script>
   </HEAD>

   <BODY>
   <div id= 'test1'>
   <div id = 'test2'>
    <input id = 'i1' type = 'text' name='i1' value='random'>
    <input type='button' value="click me" onclick="test()">

  </div>
  </div>

 </BODY>
 <HTML>

Upvotes: 0

Sanjeev Rai
Sanjeev Rai

Reputation: 6982

use:

var a1 = document.getElementById("i1");

Upvotes: 0

icaru12
icaru12

Reputation: 1582

var a1 = document.getElementById(i1);

change to

var a1 = document.getElementById('i1').value;

Upvotes: 3

Praveen
Praveen

Reputation: 56501

You're missing quotes, also to get value you should use .value.

function test() {
 var a1 = document.getElementById("i1").value;    
 alert(a1);
}

Upvotes: 0

Related Questions