ITkd
ITkd

Reputation: 21

Java script not working on id of element on chrome but works on name ( works well on Edge )

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 />

Upvotes: 0

Views: 67

Answers (3)

mcbrent
mcbrent

Reputation: 301

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 />

Upvotes: 1

Ashutosh Vyas
Ashutosh Vyas

Reputation: 419

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

Upvotes: 3

Mr. Roshan
Mr. Roshan

Reputation: 1805

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 />

Upvotes: 2

Related Questions