-1

I am wondering why in the following script comment 1 and comment 2 dosent work I know that we can access directly element by id without passing by "form" however am asking the question for educational purpose Thank you

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>test</title>
 <script>
  function ulDisply()
  {
  //var element = document.myform.getElementsByName("name1")[0].value;//1
  //var element = document.myform.getElementsById("id1").value;//2
  //var element = document.myform.elements[0].value;//3
  var element = document.myform.d.value;//4
  document.write("you number is "+ element +"<br>");
  }
 </script>
</head>
<body>
 <form name="myform">
  <input type="number" name="n" id="d">
  <input  type="submit" onclick="ulDisply()">  
 </form>
</body>
</html>

3 Answers3

1

Comment 1 :

var element = document.myform.getElementsByName("name1")[0].value;

doesn't work because :

  • there is no element named "name1".
  • getElementsByName is defined in the document object

Comment 2 :

var element = document.myform.getElementsById("id1").value;

doesn't work because :

  • the right name of the function is getElementById and it's defined in the document object
  • there is no element whose id is "id1"

When corrected, it works :

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>test</title>
 <script>
  function ulDisply()
  {
  var element = document.getElementById("d").value;//2
    


  document.write("you number is "+ element +"<br>");
  }
 </script>
</head>
<body>
 <form name="myform">
  <input type="number" name="n" id="d">
  <input type="button" value="Ok" onclick="ulDisply()">
 </form>
</body>
</html>
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
  • @Quentin getElementsByTagName is defined in HTMLElement. getElementsByName is not. Source : https://developer.mozilla.org/fr/docs/Web/API/Element/getElementsByTagName – Guillaume Georges May 29 '18 at 14:36
-1

You can use:

var element = document.getElementById("d").value;
ahajib
  • 12,838
  • 29
  • 79
  • 120
puja
  • 17
  • 3
-1

You need to change the code to be:

<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <script>
            function ulDisply()
            {
            var element = document.getElementsByName("n")[0].value;//1
            //var element = document.getElementById("d").value;//2
            //var element = document.myform.elements[0].value;//3
            //var element = document.myform.d.value;//4
            document.write("you number is "+ element +"<br>");
            }
        </script>
    </head>
    <body>
        <form name="myform">
            <input type="number" name="n" id="d">
            <input  type="submit" onclick="ulDisply()">     
        </form>
    </body>
    </html>
mbadeveloper
  • 1,272
  • 9
  • 16