在单击按钮时添加到链接的文本字段中键入数字

时间:2017-06-02 08:46:03

标签: javascript html forms

我在stackoverflow和网页上搜索了我的问题的答案,但找不到合适的解决方案。

我正在尝试创建一个文本字段和按钮,以便用户可以在文本字段中输入一个数字,当他们单击按钮时,它会将他们带到一个URL,并将该数字添加到URL的末尾。< / p>

例如http://www.website.com/trackingid/NUMBERHERE

如果用户在文本字段中键入000000然后点击按钮,则导航的URL将为http://www.website.com/trackingid/000000

任何帮助都非常感激。

由于

3 个答案:

答案 0 :(得分:0)

有两种解决方法:

  • 您可以使用JavaScript的window.location
  • 您可以将按钮设为链接,然后将其更改为href

使用window.location

让我们假设您的html结构如下所示:

<form>
    <!-- The field in which the user types the number -->
    <input type="text" id="number" placeholder="Enter number here" />

    <!-- The button -->
    <button onclick="forward();">Send</button>
</form>

单击该按钮时,将调用forward() javascript方法。此方法如下所示:

function forward() {
    // select the input field
    number = document.getElementById("number");
    // forward to the new page
    window.location = "http://www.website.com/trackingid/" + number.value;
}

更改链接的href

现在结构如下:

<form>
    <!-- The field in which the user types the number -->
    <input type="text" oninput="changeLink(this.value);" placeholder="Enter number here" />

    <!-- The button -->
    <a id="buttonLink"><button>Send</button></a>
</form>

请注意<a> - 标记除了ID之外仍然是完全空的。

oninput=调用JavaScript函数changeLink();,并在其中写入或删除内容时将其当前值作为参数。

此功能应如下所示;

function changeLink(value) {
    // select the link
    link = document.getElementById("buttonLink");
    // change it's href
    link.href = "http://www.website.com/trackingid/" + value
}

我希望这会有所帮助。如果您有任何疑问,请随时提出。

答案 1 :(得分:-1)

你需要JavaScript才能做到这一点。

HTML:

<input type="text" id="inputId">
<button type="button" id="buttonId">Click me</button>

JavaScript的:

document.getElementById('buttonId').addEventListener('click', function() {
     window.location.href = "http://www.website.com/trackingid/" + document.getElementById('inputId').value;
});

答案 2 :(得分:-1)

解决了您的问题,请查看我的解决方案

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <title>nirajpatel.mdl@gmail.com</title>
</head>
<body>
  <input type="text" id="num" name="num">
  <button id="button">Go Url</button>
</body>
<script type="text/javascript">
   $(document).ready(function(){
    url = "http://www.website.com/trackingid/";
    $("#button").click(function(){
        var num = $("#num").val();

        window.location.replace(url+num);
    });
});
</script>
</html>