user1300214
user1300214

Reputation:

JQuery .val not working

I've checked a number of related questions/answers on SO but can't find a solution. I have the following code:

    <html>
    <head>
    <title>Admin</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="#">

    <script src="jquery-3.3.1.js"> </script>
    </head>
    <body>
    <div>Test area</div>
    <br/>

    <script>
        document.write('<button onclick="updateFunc()">TEST</button>');
        document.write('<input type="text" id="mytext">');

        function updateFunc()
        {
            document.write($('mytext').val());
        }
    </script>
    </body>
    </html>

The output When I click the TEST button is:

    undefined

Don't know what I'm doing wrong here. I've tried moving things around, e.g. order of javascript, taken the HTML out into the HTML body rather than "printing" it in the JS, but still I keep getting undefined. I inspected the element and I get:

    <input type="text" id="mytext">

in the browser.

Upvotes: 3

Views: 1100

Answers (2)

Martin D.
Martin D.

Reputation: 2090

You forgot the "#" in your jQuery selector.

function updateFunc()
{
   document.write($('#mytext').val());
}

Upvotes: 2

Sajib Khan
Sajib Khan

Reputation: 24156

Change to $('#mytext').val() since it is ID (#) selector.

<script>
    document.write('<button onclick="updateFunc()">TEST</button>');
    document.write('<input type="text" id="mytext">');

    function updateFunc()
    {
        document.write($('#mytext').val());
    }
</script>

Upvotes: 3

Related Questions