0

Why this code doesn't work? is "id" attribute required?

<html>
<head>
<script language="JavaScript">
  function pprint(){
   var a = tf.value;
   document.write(a);
     }
 </script>
</head>
<body>
<input type="text" name="tf"  value="Test">
<input type="button" onClick="pprint()" value="print" >
</body>
</html>

Thanks!

2
  • 3
    "doesn't work" is not an error message or a problem description. Commented Feb 5, 2013 at 16:27
  • 5
    Also document.write() is not what you think it is. Commented Feb 5, 2013 at 16:28

4 Answers 4

5

In a form, the name attribute is required to fill the $_POST or $_GET global variables with a (name, value) pair.

Javascript will not identify an element from only the name. So, you would be better off using the id attribute.

<input type="text" name="tf" id="tf"  value="Test">

And in your Javascript, you can directly call document.getElementById('tf') to get the element.

Something like this.

document.write(document.getElementById('tf').value);
Sign up to request clarification or add additional context in comments.

Comments

2

Two changes. 'tf' is an 'id' and get the element in the javascript. And also 'alert' as suggested above.

<html>
<head>
<script language="JavaScript">
  function pprint(){
   var tf = document.getElementById('tf');
   var a = tf.value;
   alert(a);
  }
 </script>
</head>
<body>
<input type="text" id="tf"  value="Test">
<input type="button" onClick="pprint()" value="print" >
</body>
</html>

Comments

1

Why this code doesn't work?

Javascript doesn't give you a ready to use handle on the element like you're expecting. You'll have to get the element by its name, ID, tag name or through its parent form (if it had one).

is "id" attribute required?

No, the ID is not required to get a handle on the element. Example of getting the element by name:

function pprint(){
    var a = document.getElementsByName("tf")[0].value;
    console.log(a);
}

Comments

1

While using JavaScript, if you want to access any element, you can choose to use:

  1. document.getElementById (id)
  2. document.getElementByName] (name)

You can use following code:

<script language="JavaScript">
  function pprint(){
    // If you want to use element Id
      var a = document.getElementById('tf').value;
      document.write(a);
    // If you want to access by element name
      var b = document.getElementsByName('tf')[0].value;
      document.write(b);
 }
 </script>

Working demo on JsFiddle

  1. document.getElementById on W3 Schools
  2. document.getElementByName on W3 Schools

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.