텍스트 상자에서 Enter를 누를 때 HTML 버튼을 트리거하는 방법은 무엇입니까?
그래서 지금까지 가지고있는 코드는 다음과 같습니다.
<fieldset id="LinkList">
<input type="text" id="addLinks" name="addLinks" value="http://">
<input type="button" id="linkadd" name="linkadd" value="add">
</fieldset>
그것은 아닙니다 <form>
그리고 그것은 내에있는 단지입니다 <div>
. 그러나 textbox
"addLinks"라는 이름에 무언가를 입력 할 때 사용자가 Enter 키를 누르고 "linkadd" button
를 트리거하여 JavaScript 함수를 실행할 수 있기를 바랍니다 .
어떻게 할 수 있습니까?
감사
편집 : 이 코드를 찾았지만 작동하지 않는 것 같습니다.
$("#addLinks").keyup(function(event){
if(event.keyCode == 13){
$("#linkadd").click();
}
});
$(document).ready(function(){
$('#TextBoxId').keypress(function(e){
if(e.keyCode==13)
$('#linkadd').click();
});
});
js가없는 솔루션이 있습니다.
기본으로 설정할 type=submit
버튼과 type=button
다른 버튼 으로 설정 합니다. 이제 아래 양식에서 모든 입력 필드에서 Enter 키를 Render
누르면 버튼이 작동합니다 (양식의 두 번째 버튼 임에도 불구하고).
예:
<button id='close_renderer_button' class='btn btn-success'
title='Перейти к редактированию программы'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
title='Построить фрактал'
type=submit
formaction='javascript:alert("Bingo!");'>
<span class='glyphicon glyphicon-send'> </span> Render
</button>
FF24 및 Chrome 35에서 테스트되었습니다 ( formaction
html5 기능이지만 type
그렇지 않음).
2019 년입니다.
사용하지 마세요 keypress
keypress
이벤트가되는 트리거하지 유저가 눌렀을 때에 어떤 문자를 생성하지 않는 키 등을, Tab, Caps Lock, Delete, Backspace, Escape, 왼쪽 및 오른쪽 Shift, 기능 키 ( F1- F12).keypress
이벤트 Mozilla 개발자 네트워크keypress
키가 때 이벤트가 해고 아래로 누르면 , 그 키는 보통 문자 값을 생성합니다 .input
대신 사용하십시오 .더 이상 사용되지 않습니다.
keypress
이벤트 UI 이벤트 (2018 년 11 월 8 일에 게시 된 W3C 작업 초안)- 참고 | 이
keypress
이벤트는 전통적 으로 물리적 키가 아닌 문자 값 을 감지하는 것과 관련이 있으며 일부 구성의 모든 키에서 사용하지 못할 수 있습니다. - 경고 |
keypress
이벤트 유형 참조 완전성 본 명세서에 정의되어 있지만, 이 규격은 deprecates 이벤트 형의 사용. 편집 컨텍스트에서 작성자는beforeinput
대신 이벤트를 구독 할 수 있습니다 .
- 참고 | 이
사용하지 마세요 KeyboardEvent.keyCode
- 더 이상 사용되지 않습니다.
KeyboardEvent.keyCode
Mozilla 개발자 네트워크Deprecated | This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
What should I use then? (The good practice)
// Make sure this code gets executed after the DOM is loaded.
document.querySelector("#addLinks").addEventListener("keyup", event => {
if(event.key !== "Enter") return; // Use `.key` instead.
document.querySelector("#linkadd").click(); // Things you want to do.
event.preventDefault(); // No need to `return false;`.
});
- Replace the
button
with asubmit
- Be progressive, make sure you have a server side version
- Bind your JavaScript to the
submit
handler of the form, not theclick
handler of the button
Pressing enter in the field will trigger form submission, and the submit handler will fire.
You could add an event handler to your input like so:
document.getElementById('addLinks').onkeypress=function(e){
if(e.keyCode==13){
document.getElementById('linkadd').click();
}
}
It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.
First of all add jquery library file jquery and call it in your html head.
and then Use jquery based code...
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage()
with your functionality.
$('#addLinks').keypress(function(e) {
if (e.which == 13) {
sendMessage();
e.preventDefault();
}
});
Based on some previous answers, I came up with this:
<form>
<button id='but' type='submit'>do not click me</button>
<input type='text' placeholder='press enter'>
</form>
$('#but').click(function(e) {
alert('button press');
e.preventDefault();
});
Take a look at the Fiddle
EDIT: If you dont want to add additional html elements, you can do this with JS only:
$("input").keyup(function(event) {
if (event.keyCode === 13) {
$("button").click();
}
});
I found w3schools.com howto, their try me page is at the following.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter
This worked in my regular browser but did not work in my php app which uses the built in php browser.
After toying a bit I came up with the following pure JavaScript alternative that works for my situation and should work in every other situation:
function checkForEnterKey(){
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
}
function buttonClickEvent()
{
alert('The button has been clicked!');
}
HTML Press the enter key inside the textbox to activate the button.
<br />
<input id="myInput" onkeyup="checkForEnterKey(this.value)">
<br />
<button id="myBtn" onclick="buttonClickEvent()">Button</button>
<input type="text" id="input_id" />
$('#input_id').keydown(function (event) {
if (event.keyCode == 13) {
// Call your function here or add code here
}
});
I am using a kendo button. This worked for me.
<div class="form-group" id="indexform">
<div class="col-md-8">
<div class="row">
<b>Search By Customer Name/ Customer Number:</b>
@Html.TextBox("txtSearchString", null, new { style = "width:400px" , autofocus = "autofocus" })
@(Html.Kendo().Button()
.Name("btnSearch")
.HtmlAttributes(new { type = "button", @class = "k-primary" })
.Content("Search")
.Events(ev => ev.Click("onClick")))
</div>
</div>
</div>
<script>
var validator = $("#indexform").kendoValidator().data("kendoValidator"),
status = $(".status");
$("#indexform").keyup(function (event) {
if (event.keyCode == 13) {
$("#btnSearch").click();
}
});
</script>
'IT story' 카테고리의 다른 글
Android 애플리케이션에서 두 개의 SQLite 테이블을 조인하려면 어떻게해야합니까? (0) | 2020.08.29 |
---|---|
AttributeError : '모듈'개체에 '테스트'속성이 없습니다. (0) | 2020.08.29 |
TwoWay 또는 OneWayToSource 바인딩은 읽기 전용 속성에서 작동 할 수 없습니다. (0) | 2020.08.28 |
C # Regex에서 캡처 된 그룹의 이름을 어떻게 얻습니까? (0) | 2020.08.28 |
JavaFX 및 OpenJDK (0) | 2020.08.28 |