Get input text field from HTML into JavaScript and

2019-03-07 00:22发布

问题:

How get input text field from HTML into JavaScript and go to URL?

I'm building one WebPage where you type some word into the input field and the Java gets this string and check if this string is equal to another, if it is go to some URL.

My code is:

 <input type="text" name="procura" id="procura" />
  <script>
  name = oForm.elements["name"].value;

  if (name.equals("Advogados"))
 {
     window.location = "http://jornalexemplo.com.br/lista%20online/advogados.html"
     //do something
 };
  </script>

Can you give me some lights?

回答1:

Note, I've used the jquery library here in my example as it makes setting up the listeners to handle these events easier.

You're referencing oForm in your code, but I don't see that in your examples... so I would think that you will find this easier if you wrap the in a form tag, with a particular id (procura)

<div>
    <form method="get" id="procura">
        <input type="text" name="procura" id="procura_texto"  placeholder="Procurar"/>
    </form>
</div>

Then capture the result using the id of the input element (procura_texto), and jquery's val() method and prevent the form from being submitted using the method preventDefault():

$("#procura").on("submit", function(event){     

    // prevent form from being submitted
    event.preventDefault();

    // get value of text box using .val()
    name = $("#procura_texto").val();

    // compare lower case, as you don't know what they will enter into the field
    if (name.toLowerCase() == "advogados")
    {
        // redirect the user.. 
        window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
    }
    else
    {
        alert("no redirect..(entered: " + name + ")");
    }
});

here's a jsfiddle for you to play with: http://jsfiddle.net/zwbRa/5/



回答2:

Use window.location.href = "your url".