How to get the value of an HTML input and put into a "href" attribute?

Asked

Viewed 56 times

0

<h2>Pesquisar Usuários</h2>

<form action="">
    <input type="text" id="name" name="name">
    <a href="#" onclick="window.open('/Usuarios/Usuario?id=' + input)" target"_blank">Buscar</a>
</form>

<script>
    var input = document.getElementsByName('name').values
</script>

This is the way out:

https://localhost:44339/Usuarios/Usuario?id=function%20values()%20{%20[native%20code]%20}

When my goal was to get this output, for example:

https://localhost:44339/Usuarios/Usuario?id=1

I have tried to get the value of all that was form.

  • 1

    Your code has errors in Html: target is missing a =, and in Js Document.Getelementsbyname returns a NodeList, that is, an array with several elements with that name, even if in Html there is only 1, then you have to take the input like this (Document.getElementsByName('name')[0].value) and how you can see tbm is value and not values!

  • <H2>Search Users</H2> <input type="number" id="search" name="search"> <a href="#" onclick="window.open('/Users/User?id=' + input)" target="_Blank">Search</a> <script> input var = Document.getElementByName('search')[0]. value </script> My code is like this now and the link is leaving without the value I put in the input: https://localhost:44339/Users/User? id=

  • If the input has the name input as the mounted url will be the final id. https://localhost:44339/Users/User? id=1... would not be https://localhost:44339/Users/username .... input Saira capture will be the name typed and will not be returned a number other than what.

  • Give a hint in your doubt maybe I can help.

1 answer

0

I believe this solves your problem:

<html>
    <body>
        <h2>Pesquisar Usuários</h2>

        <form action="#">
            <input type="text" id="name" name="name">
            <button onclick="buscarUsuarios()">Buscar</button>
        </form>
        
        <script>
            function buscarUsuarios() {
                let inputValue = document.querySelector('#name').value;
                window.open('/Usuarios/Usuario?id=' + inputValue);
            }
        </script>        
    </body>
</html>

Problems

  • Attempt to select input by method document.getElementsByName, which returns an array-like, not the HTML element directly.
  • Expectation to access the value returned by a "values" property, which does not exist

Solutions

  • Select input by its ID, through document.querySelector, which already returns the HTML element directly
  • Get input value through property value

Browser other questions tagged

You are not signed in. Login or sign up in order to post.