简体   繁体   中英

Make a link 'enter-clickable'

If you have a normal form:

<form method='post' action='#'>
<input type='text' name='#' />
<input type='submit' value='Submit />
</form>

Then you can fill in the input field, and press enter. However, I am using a link to do my work so:

<form method='post' action='#'>
<input type='text' name='#' />
<a href='#' class='button' onclick='get_form(this).submit();'>Submit</a>
</form>

That works like a charm, however, I want it to inherit the 'enter-clickable' that the normal submit field has. Is that possible through some javascript?

$('#your_input_textfeild_id').keypress(function(e) {
     //check if enter is pressed
   if(e.keyCode == 13) {


    //click your link
        $('#your_submit_link_id').click();



    }
  });

try this:

<script>
   document.getElementById('TEXTBOXID').onkeypress = function(e){
      var evt = e || window.event;
      if(evt.keyCode == 13){
          get_form(this).submit();
      }
   }
</script>

You may try this

document.getElementById('my_input').onkeypress = function(e)
{
  var event = e || window.event;
  if(event.keyCode == 13 && this.value!="")
  {
     form = this.parentNode;
     if(form.tagName.toLowerCase() == "form") 
     {  
        form.submit();
     } 
  }
}

You have to add an id to your text box and replace my_input with it.

I think the correct way to do this is to actually include a

<input type="submit"  >

which you can then style to be hidden. Alternatively, just style the submit element to look the way you want. My reason for this is that the browser looks for that submit element and that's how the enter key gets assigned to submit the form. And I somehow think it's better to let the browser handle matters like that rather than using JavaScript to capture a keypress event.

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