HTML onchange 이벤트가 작동하지 않습니다.
실험을 해보려고합니다. 내가 원하는 것은 사용자가 텍스트 상자에 무언가를 입력 할 때마다 대화 상자에 표시된다는 것입니다. 내가 사용 onchange
이 일어날 수 있도록 이벤트 속성을하지만 일을하지 않습니다. 작동하려면 제출 버튼을 눌러야합니다. 나는 AJAX에 대해 읽었고 이것에 대해 배우려고 생각하고 있습니다. 작동하려면 AJAX가 여전히 필요합니까 아니면 간단한 JavaScript로 충분합니까? 도와주세요.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange
컨트롤이 흐려질 때만 트리거됩니다. onkeypress
대신 시도하십시오 .
.on('input'...
jQuery 1.7 이상에서 입력 (붙여 넣기, 키업 등)에 대한 모든 변경 사항을 모니터링하는 데 사용 합니다.
정적 및 동적 입력의 경우 :
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
정적 입력에만 해당 :
$('.my-class').on('input', function(){
alert('Input changed');
});
정적 / 동적 예제가있는 JSFiddle : https://jsfiddle.net/op0zqrgy/7/
마우스 클릭을 사용하여 입력 필드의 내용을 변경할 수 있기 때문에 키 입력을 확인하는 것은 부분적인 해결책 일뿐입니다. 텍스트 필드를 마우스 오른쪽 버튼으로 클릭하면 키 입력없이 값을 변경하는 데 사용할 수있는 잘라 내기 및 붙여 넣기 옵션이 있습니다. 마찬가지로 자동 완성이 활성화 된 경우 필드를 마우스 왼쪽 버튼으로 클릭하고 이전에 입력 한 텍스트의 드롭 다운을 가져올 수 있으며 마우스 클릭을 사용하여 선택 항목 중에서 선택할 수 있습니다. 키 입력 트랩은 이러한 유형의 변경 사항을 감지하지 못합니다.
안타깝게도 적어도 내가 아는 한 변경 사항을 즉시보고하는 "onchange"이벤트는 없습니다. 그러나 모든 경우에 작동하는 솔루션이 있습니다. setInterval ()을 사용하여 타이밍 이벤트를 설정합니다.
입력 필드에 "city"라는 ID와 이름이 있다고 가정 해 보겠습니다.
<input type="text" name="city" id="city" />
"city"라는 전역 변수가 있습니다.
var city = "";
페이지 초기화에 다음을 추가하십시오.
setInterval(lookForCityChange, 100);
그런 다음 lookForCityChange () 함수를 정의하십시오.
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
이 예에서 "city"값은 100 밀리 초마다 확인되며 필요에 따라 조정할 수 있습니다. 원한다면 lookForCityChange ()를 정의하는 대신 익명 함수를 사용하십시오. 코드 또는 브라우저가 입력 필드에 대한 초기 값을 제공 할 수 있으므로 사용자가 작업을 수행하기 전에 "변경"에 대한 알림을받을 수 있습니다. 필요에 따라 코드를 조정하십시오.
10 분의 1 초마다 발생하는 타이밍 이벤트의 아이디어가 부적절 해 보이면 입력 필드가 포커스를받을 때 타이머를 시작하고 흐림시 종료 (clearInterval () 사용) 할 수 있습니다. 포커스를받지 않고 입력 필드의 값을 변경할 수 없다고 생각하므로 이러한 방식으로 타이머를 켜고 끄는 것이 안전 할 것입니다.
HTML5 는 oninput
모든 직접적인 변경 사항을 포착 하는 이벤트를 정의합니다 . 그것은 나를 위해 작동합니다.
onchange
입력 요소에 대한 변경 사항이 사용자에 의해 커밋 된 경우에만 발생하며 대부분의 경우 요소가 포커스를 잃을 때입니다.
요소 값이 변경 될 때마다 함수가 실행되도록하려면 oninput
이벤트를 사용해야합니다 . 값이 사용자의 마우스 (예 : 붙여 넣거나 자동 채우기 등)로 변경 될 수 있으므로 키 업 / 다운 이벤트보다 낫습니다.
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event)
with <select>
. With <input>
you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is
"input"
("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-inputThe two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
try onpropertychange
. it only works for IE.
참고URL : https://stackoverflow.com/questions/6290442/html-input-type-text-onchange-event-not-working
'your programing' 카테고리의 다른 글
문자열이 유효한 Windows 디렉터리 (폴더) 경로인지 확인 (0) | 2020.10.16 |
---|---|
소프트 키보드의 ActionBar SearchView 자동 축소 닫기 (0) | 2020.10.16 |
개체를 쓰는 동안 힘내가 멈춤 (0) | 2020.10.15 |
vim : 여러 줄의 처음 2 개 공백 삭제 (0) | 2020.10.15 |
어노테이션 만 사용하여 (web.xml 없음) JAX-RS 애플리케이션을 설정하는 방법은 무엇입니까? (0) | 2020.10.15 |