2012-05-28 23 views
9

我有一個表單內的輸入元素,我希望能夠提取它的值時,值的變化。看看這個小提琴:http://jsfiddle.net/spryno724/WaBzW/1/jQuery監聽所有文本輸入變化

通過使用change事件,我可以在輸入失去焦點時顯示來自文本輸入的值。但是,當表單重置或JavaScript清除文本輸入的值時,該值不會更新。

有沒有辦法,我可以監聽,當任何變化到一個文本輸入控制方面將派出一個特定的事件?

我想避免變通方法,例如在窗體重置時收聽,或者按下清除按鈕時。這是我的應用程序所做的一個簡化示例,如果我嘗試完成所有這些,它會變得非常快。

謝謝你的時間。

+1

叫我只是對這個同樣的問題,今天的工作。 jQuery'.on'事件應該可以解決這個問題,但是我無法讓它工作。 $(「#ElementID」)。on(「input change property change paste keyup」,handler)'...... –

+0

嗯......我以前從來沒有用過'.on()'。我會研究它 –

+0

我以前使用過'.live()',但從1.7版本開始已被棄用,'.on()'現在是首選方法 –

回答

10
$(document).ready(function() { 
    $('input.clear').click(function() { 
     $('input.input').val(''); 
     $('p.display').text('The value of the text input is: '); 
    }); 

    $('input.input').on('keyup change', function() { 
     $('p.display').text('The value of the text input is: ' + $(this).val()); 
    }); 
})​ 

DEMO 1

也許這個解決方案可以幫助你:

$(document).ready(function() { 
    $('input.clear, input[type=reset]').on('click', function() { 
     $('input.input').val('').change(); 
     $('p.display').text('The value of the text input is: '); 
    }); 

    $('input.input').on('keyup change', function() { 
     $('p.display').text('The value of the text input is: ' + $(this).val()); 
    }); 
});​ 

DEMO 2

+0

謝謝,但按重置將不會更新輸入上方的文本。 –

+1

什麼時候數據被設置爲來自另一個函數的輸入值? '.keyup'不會覆蓋那個 –

+0

我很欣賞你的輸入,但是我也提到過我會避免變通,比如聽窗體重置時,或者按下清除按鈕時。是我的應用程序所做的一個簡化示例,如果我嘗試完成所有這些,它會變得非常快。「 –

-1

嘗試

$('#input').live('change',function() {   }) 
+0

'.live()'是每當有新的元素被動態地添加到頁面中並且必須附加事件時:http://api.jquery.com/live/ 。 –

+6

不要使用'.live()'它已從1.7版本棄用 –

+0

好知道!!! –

0

覆蓋的jQuery

val方法

HTML

<input id='myInput' name='myInputField' value='v1'>

JS

var myInput = $('#myInput'); 

//this will not trigger the change event 
myInput.val('v2'); 

//override val method 
var oldVal = myInput.val; 
myInput.val = function(value){ 
    var returnVal = oldVal.call(this,value); 
    myInput.change(); 
    return returnVal; 
} 

// this will trigger the change event 
// myInput.val is overridden 
myInput.val('v3'); 

注意這將工作僅如果val方法是從myInput可變