有一个下拉列表和输入框。如果在下拉列表中选择Aadhar,我将为输入框分配keydown事件,该事件仅采用数字。在PASSPORT的情况下,我正在更改带有字母数字字符的keydown事件。
function changeDocumentType(pthis) {
//dropdown change
var htmlid = "#" + pthis.id;
var doctype = $(htmlid+':selected').val();
populateValidations(doctype,"docId");
}
function populateValidations(doctype,inputId){
$("#"+inputId).removeAttr("onkeydown");
$("#"+inputId).removeClass("onlyNumeric");
$("#"+inputId).removeClass("alphabetNumeric");
if(doctype === "1"){
//aadhar
$("#"+inputId).addClass("onlyNumeric");
$("#"+inputId).attr("onkeydown", "return inputOnlyNumberTablet(this,event,12)");
}
if(doctype === "2") {
//passport
$("#"+inputId).addClass("alphabetNumeric");
$("#"+inputId).attr("onkeydown", "return inputOnlyAlphaNumericTablet(this,event,10)");
}
}
function inputOnlyAlphaNumericTablet(pthis, event, length){
$('.alphabetNumeric').on('input', function(event) {
if (pthis.value.length <= parseInt(length, 10)) {
pthis.value = pthis.value.replace(/[^a-z0-9]/gi, '');
} else {
pthis.value = pthis.value.substr(0, pthis.value.length - 1);
}
});
}
}
function inputOnlyNumberTablet(pthis, event, length){
$('.onlyNumeric').on('input', function(event) {
if (pthis.value.length <= parseInt(length, 10)) {
pthis.value = pthis.value.replace(/[^0-9]/g, '');
} else {
pthis.value = pthis.value.substr(0, pthis.value.length - 1);
}
});
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="docId" type="text" value="" enabled="enabled" >
<select style="" value="" enabled="enabled" onchange="changeDocumentType(this)" id="DocumentListFile">
<option value="">Select</option>
<option value="1">Aadhar ID</option>
<option value="2">PassPort</option>
</select>
&#13;
如果选择aadhar作为护照,也只接受数字输入。此代码是Android设备的返回。任何解决方案 感谢。
答案 0 :(得分:0)
您必须在绑定新的侦听器之前删除其他keydown侦听器,否则每次执行下拉列表时都会获得多个侦听器,
简单地从元素中删除属性不会取消绑定事件。
这不是一个完整的复制/粘贴答案。这是一个例子,你可以调整你的需求。我刚接受了分配监听器并更改它的代码部分。
function populateValidations(doctype,inputId){
var inp = $("#"+inputId); // get this once. Easier if there is a name change etc
inp.unbind('keydown'); // unbind any keydown event that may exist
inp.removeClass("onlyNumeric");
inp.removeClass("alphabetNumeric");
if(doctype === "1"){
//aadhar
inp.addClass("onlyNumeric");
// add your keydown
inp.keydown(function(){ return inputOnlyNumberTablet(this,event,12);});
}
if(doctype === "2") {
//passport
inp.addClass("alphabetNumeric");
inp.keydown(function(){return inputOnlyAlphaNumericTablet(this,event,10);});
}
}