0

I am trying to reference a text box and a form by id . Below is the bit of javascript code that works on Microsoft edge but will not work on Chrome. Appreciate any help.

<script type="text/javascript">
    function sayHello() {
        var name4 = document.form1.txthello.value; // does not work

    }

<body>
<form id="form1" name="myForm1">
    Name : <input type="text" id="txthello" name="myTxthello" value="" />
    <br />
    <input type="button" id="btnHello" value="Hello" onclick="sayHello()" />
    <hr />
ITkd
  • 21
  • 4
  • What is your question? _Why it works_ on Edge? Why you _need to reference the `name` attribute_? How to replace this _obsolete DOM traversal approach_ with modern DOM methods? You haven’t asked a _specific, answerabe_ question. – Sebastian Simon Jun 20 '18 at 05:08
  • You shouldn't rely on this former non-standard "feature": [javascript - Do DOM tree elements with ids become global variables?]https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) – Andreas Jun 20 '18 at 05:12
  • Edge supports some totally non standard features implemented by Internet Explorer for legacy reasons. Accessing forms as named properties of `document` is one of them. Do no use "it works well in Edge" to judge fitness of a site for the web. – traktor Jun 20 '18 at 07:22
  • Thanks very much for all the tips... Is there is a good source ( if any one of you know ) to use as a reference with regards to Javascript so I can follow the correct way ? – ITkd Jun 20 '18 at 11:56

3 Answers3

3

Have you tried using document.getElementById('txthello').value

Ashutosh Vyas
  • 419
  • 4
  • 17
2

Try this:

    function sayHello() {
        var name4 = document.getElementById("txthello").value; 
        alert(name4);
    }
<form id="form1" name="myForm1">
    Name : <input type="text" id="txthello" name="myTxthello" value="" />
    <br />
    <input type="button" id="btnHello" value="Hello" onclick="sayHello()" />
    <hr />
Mr. Roshan
  • 1,777
  • 13
  • 33
1

Try this one. This works on Chrome.

I've added a closing and replaced document.form1.txthello.value; to document.getElementById('txthello').value;

<script type="text/javascript">
        function sayHello() {
            var name4 = document.getElementById('txthello').value; 
            console.log(name4);
            
        }
</script>
<form id="form1" name="myForm1">
    Name : <input type="text" id="txthello" name="myTxthello" value="" />
    <br />
    <input type="button" id="btnHello" value="Hello" onclick="sayHello()" />
    <hr />
mcbrent
  • 301
  • 2
  • 12