我目前在我的一项 SurveyGizmo 调查中执行了以下 Javascript 操作。
其目的是计算某人指定其出生日期的确切年龄(按特定日期)。
但是,我们经常在调查中预先填充信息。问题是,当 dob 文本框中已经预填充了日期时,脚本不会触发。 有没有办法确保在加载页面以及更改文本框时年龄文本框更新?
感谢您提供的任何帮助/
$SG(document).ready(function(){
if ($SG('body').attr('id') != 'app') {
var textbox = $SG('#sgE-2604126-33-6-element'); //dob box
$tgtbox = $SG("#sgE-2604126-33-254-element"); //age box
$minage = 21; //minimum age
$errortxt = 'You must be at least ' + $minage + ' years old to continue';
textbox.change(function(){
console.log($SG(this).val());
var birth = $SG(this).val();
function getAge(birth) {
var d = new Date(2016,3,16);
var n = d.getTime();
console.log(n);
var c = Date.parse(birth);
console.log(c);
var a = (d - c) /(1000*60*60*24*365);
var result=(a*100)/100;
console.log(result);
$tgtbox.val(result);
//alert(result);
}
getAge(birth);
});
}
//submit validation
$('.sg-survey-form').submit(function(e){
if($tgtbox.val() < $minage) {
//alert($tgtbox.val());
//alert($minage);
$('.sg-error-message').text($errortxt).fadeIn('slow');
e.preventDefault();
}
}); //end submit validation
});
在文本框中发生更改事件之前,代码不会设置年龄显示。如果文本框中预加载了某些内容,则需要初始化年龄显示。
要初始化年龄显示,看起来您只需在加载时调用textbox.change
触发的代码一次。喜欢这个:
function setAge() {
console.log($SG(this).val());
var birth = $SG(this).val();
function getAge(birth) {
var d = new Date(2016,3,16);
var n = d.getTime();
console.log(n);
var c = Date.parse(birth);
console.log(c);
var a = (d - c) /(1000*60*60*24*365);
var result=(a*100)/100;
console.log(result);
$tgtbox.val(result);
//alert(result);
}
getAge(birth);
}
// run upon textbox change event
textbox.change(function() { setAge(); } );
// run right now
setAge();
或者这是没有不必要的位的代码片段:
function setAge() {
console.log($SG(this).val());
var birth = $SG(this).val();
var d = new Date(2016,3,16);
var n = d.getTime();
var c = Date.parse(birth);
var a = (d - c) /(1000*60*60*24*365);
var result=(a*100)/100;
$tgtbox.val(result);
}
// update age upon textbox change event
textbox.change(function() { setAge() } );
// update age right away
setAge();
看起来您必须通过定期运行检查功能来做到这一点。
下面是一些代码片段:
$.fn.allchange = function (callback) {
var me = this;
var last = "";
var infunc = function () {
var text = $(me).val();
if (text != last) {
last = text;
callback();
}
setTimeout(infunc, 100);
}
setTimeout(infunc, 100);
};
$("#myInput").allchange(function () {
alert("change!");
});