从HTML获取输入文本字段到JavaScript并转到URL

时间:2013-06-18 15:05:06

标签: javascript html text input field

如何从HTML输入文本字段到JavaScript并转到URL?

我正在构建一个WebPage,您在输入字段中输入一些单词,Java将获取此字符串并检查此字符串是否与另一个字符串相等,如果它转到某个URL。

我的代码是:

 <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>
你可以给我一些灯吗?

2 个答案:

答案 0 :(得分:1)

使用window.location.href =“你的网址”。

答案 1 :(得分:0)

注意,我在我的示例中使用了 jquery 库,因为它使设置侦听器更容易处理这些事件。

您在代码中引用了oForm,但我在您的示例中没有看到...所以如果您将表单标记包装在一个表单标记中,我会认为您会发现这更容易特定身份证(procura

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

然后使用输入元素的id(procura_texto)和jquery的val()方法捕获结果,并阻止使用方法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 + ")");
    }
});

这里有一个jsfiddle供你玩:http://jsfiddle.net/zwbRa/5/