Append URL with form input

送分小仙女□ 提交于 2019-12-31 03:37:06

问题


This is my first attempt to write anything in javascript, although this does exactly as intended, I am sure it can be done simpler. Not that this script is all that useful, just an exercise in learning something new. I was also trying not to use the evil document write.

So what is the more elegant way of doing this?

<html>
<body>

<input name="abc" type="text" id="foo">
<button onclick="AddInputValue()">Submit</button>

<p id="displayURL"></p>

<script>
function AddInputValue(){
var domain = "http://site.com?abc="
var qstring = document.getElementById("foo").value;
document.getElementById("displayURL").innerHTML=domain + qstring;
}
</script>
</body>
</html>

回答1:


If you use jQuery:

<html>
    <!-- Include jQuery! -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <body>
        <form id="form1">
            <input name="abc" type="text" id="foo">
            <button type="submit">Submit</button>
        </form>

        <p id="displayURL"></p>

        <script>
            $(document).ready(function () {
                var form = document.getElementById("form1");
                $(form).submit(function () {
                    var domain = "http://site.com/?";
                    var data = $(this).serialize();

                    document.getElementById("displayURL").innerHTML = domain + data;

                    return false;
                });
            });
        </script>
    </body>
</html>

You can even add more form elements and the name of the element will match the query string. http://jsfiddle.net/3muu6/




回答2:


Just posting the example in http://jsfiddle.net/3muu6/.

Increased the number of inputs. This is basically what Google Analytics URL Builder does, and was the inspiration for this exercise.

<html>
<head>
<!-- Include jQuery! -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>

<body>
 <form id="form1">
    <input name="abc" type="text" id="foo" /><br />
    <input name="def" type="text" id="bar" /><br />
    <input name="ghi" type="text" id="tar" /><br />
    <input name="jkl" type="text" id="boo" /><br />
<button type="submit">Submit</button>
</form>
<p id="displayURL"></p>


<script>
$(document).ready(function () {
    var form = document.getElementById("form1");
    $(form).submit(function () {
        var domain = "http://example.com/?";
        var data = $(this).serialize();

        document.getElementById("displayURL").innerHTML = domain + data;

        return false;
    });
}); 
</script>
</body></html>

Now how to omit a query-string pair when the user leaves an input value blank? Hmm.



来源:https://stackoverflow.com/questions/15596927/append-url-with-form-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!