Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press enter on form input to make it lose focus

I have a form with an input box and hidden submit field:

<form action="javascript:void(0);">
    <input type="text">
    <input type="submit" style="display:none;">
</form>

I would like to make it so that when you click enter, the input box simply loses focus.

How can I accomplish this?

like image 936
Clayton Avatar asked Jul 08 '15 23:07

Clayton


3 Answers

Try this out. Please note that you need to include jquery file for this to work.

<form action="javascript:void(0);">
    <input type="text" id="txtFocus">
    <input type="submit" style="display:none;" id="btnHidden">
</form>
<script>
$("#btnHidden").on('click', function() {
        $('#txtFocus').blur();
});
</script>
like image 121
prashant Avatar answered Nov 03 '22 07:11

prashant


Give your input an id for convenience, and you can do this with this little function using plain javascript

<form action="javascript:void(0);">
    <input id="input1" type="text">
    <input type="submit" style="display:none;">
</form>
<script>
document.getElementById('input1').addEventListener('keyup',function(e){
    if (e.which == 13) this.blur();
});
</script>
like image 20
baao Avatar answered Nov 03 '22 07:11

baao


Avoid the ID lookup in the JS code by the following (tested on Firefox and Chrome). Submit by input loss of focus, possibly triggered by form submit.

function myFunction(input) {
    input.value = input.value.toUpperCase();
    return false;
}
<form onsubmit="this.textfield.blur();return false">
  <input type="text" id="textfield" onfocusout="myFunction(this)">
  <input type="submit" style="display:none;" />
</form>
like image 21
Joakim Avatar answered Nov 03 '22 07:11

Joakim