简体   繁体   中英

HTML input box without a form

I need to have an input box in a div without a form and when the user enters something and hits return, it should run a Javascript function.

There will be no submit button.

How can I do this?

要获得没有表单的输入框,我建议不要使用表单。

You will have to attach a onkeypress event and check if enter was pressed (and rune the code if it was). Tell us if you are using plain JavaScript or some library if you need examples.

It can be simply done with the help of a form as follow... i think adding form would provide great stability

<form onSubmit='alerttest(this); return false'>        
    <input type="text">         
</form>


<script language="javascript">
    function alerttest() {
        alert("Executing jolly.exe !!!!");
    }
</script>

To run a function when the user presses enter when focused on the input field, the easiest way would be to have the form tag and run the function using the form's onSubmit event (because pressing return when focused on an input field submits the form).

If you nevertheless don't want to include the form tag, you can use the onKeyPress event to catch the return key pressing and call the function from there.

Don't use the form tag. You can easily use JQuery to tie the code to the input control's key press events.

If you are unfamiliar with JQuery, just tie the code directly to the input field key press 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