简体   繁体   中英

Submit Form Contents to a URL

I'll be honest, I don't really know what the best approach here is. I've got no Javascript knowledge, but I don't think should be necessary here...It's stupidly simple.

I have a simple form. I want the user to be able to type a word and press enter or click "submit." When "X" is entered, I want them to be redirected to 'www.MyURL.com/X.html'. The only solution I could find looked like this:

<form>
<input name="solution" type="text" id="solution" maxlength="10" /><br />
<input type="button" value="submit" onclick="window.location='http://www.MYURL.com/' + this.form.solution.value + '.html'"/>
</form>

However, this doesn't allow the user to hit Enter to submit the form. I tried the below to make it a submit input, but I don't know anything about the potential operations of "onsubmit", and this one isn't working.

<form onsubmit="window.location='http://www.MYURL.com/' + this.form.solution.value + '.html'">
<input name="solution" type='text' id="solution" maxlength="10" /><br />
<input type="submit" value="submit" />

Should I be using "action=" for this event? And I don't know if "method=" plays into it.

My issue is that I can't figure out how to make the form submit its text content to a URL and then link to that URL.

You can do this all in javascript without a form. Just check the key code with each keyboard press - if it's the Enter key (13), then do your redirect.

Here's a full working page:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input type="text" id="solution" onkeyup="doSomething(event);">
<input type="button" value="Click Me" onclick="redirect();">
<script type="text/javascript">
    function doSomething(e) {
        var keyCode = e.keyCode || e.charCode;
        if (keyCode === 13) {
            redirect();
        }
    }

    function redirect() {
        window.location.href = "http://www.MYURL.com/"
            + document.getElementById("solution").value
            + ".html";
    }
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM