简体   繁体   中英

javascript go to URL from input on button press or return key

I have a page with an input field where I'd like to send the user to the URL they enter in the input, with -.html appended at the end. My HTML is as follows:

<form name="codeform"> 
<input type="text" id="code" name="code" autofocus>
</form>

<a href="#" class="button" id="submit">SUBMIT</a>

And my javascript:

$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });

When the user clicks the button, the script works as intended and the user goes to the page. But I'd also like the script to execute when the return key is pressed. Right now, when the return key is pressed, it tries to submit the form and I end up with a query string.

What is the best way to send the user to the page whether the button or return key is pressed?

Because your a.button is outside from the form, you need to add trigger to the form and the a.button too. Then just detect the Enter keycode , and done.

 $('form').submit(function(e) { e.preventDefault(); console.log(window.document.codeform.code.value + '.html') }); $('form').keydown(function(e) { if (e.which == 13) { console.log(window.document.codeform.code.value + '.html') } }); $('#submit.button').click(function() { console.log(window.document.codeform.code.value + '.html') });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <form name="codeform" id="codeform"> <input type="text" id="code" name="code" autofocus> </form> <a href="#" class="button" id="submit">SUBMIT</a>

You can add a keydown listener that only runs on enter (keycode 13), and then prevents the default form submission action:

$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });
$('#code').keydown(function (event) {
    if(event.which==13){
        event.preventDefault();//prevents form submission
        location.href = window.document.codeform.code.value + '.html';
    }
});

Since you have the logic attached to the button click() event, you can simply attach a keypress() event to the input box to subsequently execute the button click.

$("#code").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $('#submit').click();       
    }
});

However, for tidiness I usually prefer to move the logic from the click event into a separate function and call that one function from both the click() and keypress() events.

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