Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


2 Answers

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>
like image 178
Sajib Khan Avatar answered May 31 '26 20:05

Sajib Khan


You forgot the "#" in your jQuery selector.

function updateFunc()
{
   document.write($('#mytext').val());
}
like image 33
Martin D. Avatar answered May 31 '26 19:05

Martin D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!