问题描述
简短说明
每当禁用的文本框值更改时,我都想做一些事情
详细说明
我有一个禁用的文本框,其值以编程方式设置我想绑定禁用文本框的更改事件以触发其他一些功能。 这是我尝试过但不起作用的方法。
$('#Rate').change(function() {
// alert("Change Event Called");
CalculateMedicine();
});
$('input[id$=Rate]').bind("change", function () {
CalculateMedicine();
});
这两件事对我都不起作用,而且我不喜欢将函数CalculateMedicine()
放在所有可能发生Rate
文本框变化的地方的想法。所以除了这个解决方案,任何帮助都将不胜感激
1楼
如果您以编程方式更改值,则不会触发change
事件
见
一个不优雅的可能解决方案:
function checkChanges(){
if(prevRate != $('#Rate').val()){
prevRate = $('#Rate').val();
alert('changed');
}
}
var prevRate;
$(document).ready(function(){
prevRate = $('#Rate').val();
setInterval(function(){
checkChanges();
} ,500);
});
2楼
您可以为更改事件使用trigger
:
<input type="text" disabled="disabled" name="fname" class="myTextBox" ><br>
<input type="button" name="submit" id="submit" value="Submit">
Javascript:
$(".myTextBox").change(function(){
console.log("yes i m working");
});
$("#submit").click("input", function() {
$(".myTextBox").val("New value").trigger("change");
});
检查
3楼
假设您的输入在点击时禁用类或您像这样检查的其他内容
if ($( "#input" ).hasClass( "disable" )) {
Your logics and codes here //
}
//希望这会有所帮助
4楼
如果重新定义该输入的 value 属性是可能的。
<html>
<head>
<script>
function Init(){
var tE = document.querySelector('input'); //Our input field.
//We redefine the value property for the input
tE._value = tE.value;
Object.defineProperty(tE, 'value', {
get: function(){return this._value},
set: function(v){
console.log(1, 'The value changed to ' + v)
this._value = v;
this.setAttribute('value', v) //We set the attribute for display and dom reasons
//Here we can trigger our code
}
})
}
function Test(){
//In one second we are going to change the value of the input
window.setTimeout(function(){
var tE = document.querySelector('input'); //Our input field.
tE.value = 'Changed!'
console.log(0, 'Changed the value for input to ' + tE.value)
}, 1000)
}
</script>
</head>
<body onload = 'Init(); Test();'>
<input type = 'text' disabled = 'true' value = 'Initial' />
</body>
</html>
5楼
您可以通过以下代码从要触发更改事件或任何其他事件的任何位置触发更改事件。 该事件将在值更改或不更改时触发。 只需将代码放在您以编程方式更改值的位置之后。
element.dispatchEvent(new Event('change'))
let input = document.querySelector("input"); input.addEventListener("change", () => alert("Change Event is Fired")); input.value = "xyz"; input.dispatchEvent(new Event("change"));
<input type="text" disabled value="abc">